String manipulation in C#. How to extract a string from a string? - c#

My code:
string strFilePath = textBox1.text;
The textbox's text typically looks like C:\today\abc def.txt.
I want to isolate 'abc def' into its own string. That is, everything before '.txt' but after the last '\'.
The string manipulation that I'm familiar with uses Split and Last, but neither are applicable here (I think).

You're looking for Path.GetFileNameWithoutExtension().

You can use String.LastIndexOf and String.SubString methods like;
string s = #"C:\today\abc def.txt";
string ss = s.Substring(s.LastIndexOf('\\') + 1, s.IndexOf('.') - s.LastIndexOf('\\') - 1);
Console.WriteLine(ss);
Output will be;
abc def
Here a DEMO.
Or easy way, just use Path.GetFileNameWithoutExtension method
Returns the file name of the specified path string without the
extension.
string name = Path.GetFileNameWithoutExtension(#"C:\today\abc def.txt");
Console.WriteLine(name); //abc def

Related

C# Parse command line string with spaces. System.IO.Path and FileInfo fails

I'm looking for a reliable way to parse a path string that has spaces
e.g
"C:/Test has spaces/More Spaces.exe argument"
System.IO.Path.GetDirectoryName works (returns "C:/Test has spaces"), but System.IO.Path.GetFileName returns "More Spaces.exe argument". I want get the .exe and split the arguments .
The string is not double quoted so let's say I cannot modify the input string.
You should take the character index after the extension and remove the rest of the string.
like this:
string myString = "C:/Test has spaces/More Spaces.exe argument";
int index_Of_ext = myString.LastIndexOf("exe")
//including "exe"
+ 3;
string output = myString.Remove(index_Of_ext,
//starting remove
myString.Length - index_Of_ext);
//the rest of the string
in this way in the output string you miss the part after "exe" (including extension)

String concatenation using String interpolation

I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.

How can I make a string out of a complex URL address

I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();

How to split string based on another string

I have a string:
string fileName = VAH007157100_REINSTMT_20d5fe49.tiff
I want to split this at the end of REINSTMT.
string splittedFileName = fileName.split("REINSTMT")[0];
The above does not work.
How would I go about splitting it to grab everything from the left side of the word "REINSTMT"?
Try this
string splittedFileName = fileName.Split(new string[]{"REINSTMT"},
StringSplitOptions.None)[0];
In order to split based on a string rather than a char, you need to provide a second argument. See the documentation here.
What you probably want is
string splittedFileName = fileName.split(new string[] {"REINSTMT"}, StringSplitOptions.None)[0];
Another way would be with substring:
string fileName = "VAH007157100_REINSTMT_20d5fe49.tiff";
string splittedFileName = fileName.Substring(0, fileName.IndexOf("REINSTMT"));

Extracting string that is present in one string and not other

I have two strings:
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
Any of the strings could be greater here. What I need is to extract string from strtwo which is not in strone.
What I have tried is this:
IEnumerable<string> str=strtwo.Except(strone); //(returns only first character ie w)
I tried converting both strone and strtwo to string arrays but looping through each string one by one won't provide solution as strone may contain other characters in between.
What i require is to extract the entire string sequentially in strtwo that is not in strone.
you can try to extract the text from the second string in this fashion
string diff = strtwo.Replace(strone,"");
This should output you " what is your school name?" which is what you are looking out for else please do update the question with other example/cases.
The simplest way is using Replace:
string strone="what is your name?";
string strtwo="what is your name? what is your school name?";
string finalStr = strtwo.Replace(strone, "");
If your looking for something that compares more than just the First part of the strings and shows the diff on the end then have a look at the Diff Implementation, but basically your looking for This Algorithm
However if you are just looking for the difference on the end of a string look at #dasblinkenlight solution
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
string extractedString = strtwo.Replace(strone, "");
why not looking at the result of
strtwo.Split(new String[]{strone}, StringSplitOptions.RemoveEmptyEntries)
?

Categories

Resources