Strings:
string one = @"first%second";
string two = @"first%second%third";
string three = @"first%second%third%fourth";
I need to be able to separate everything that comes after the first '%' delimiter. I'd normally use split function:
string partofstring = one.Split('%').Last();
or
string partofstring = one.Split('%').[1];
However I need to be able to get:
string oneresult = @"second";
string tworesult = @"second%third";
string threresult = @"second%third%fourth";
string.Split has an overload that allows you to specify the number of splits that you want to get back. Specifying 2 as the number of splits you will get an array with the element at index 0 that you can discard and the element at index 1 that is exactly the output requested
string three = @"first%second%third%fourth";
var result = three.Split(new char[] {'%'}, 2);
Console.WriteLine(result[1]); // ==> second%third%fourth
Try this
string partofstring = one.SubString(one.IndexOf('%'));
String.SubString returns a string starting from the specified position to the end of the string.
String.IndexOf returns the first index of the specified character in the string.
Either use a different overload of string.Split
that allows you to specify the maximum number of items:
var newString = myString.Split('%', 2)[1];
Note if you're using .NET Framework, you will need to use a different overload:
var newString = three.Split(new[] { '%'}, 2)[1];
Or, calculate it yourself using IndexOf
and Substring
:
var newString = myString.Substring(myString.IndexOf('%') + 1);
I've improved the code snippet given by @Preciousbetine
var partofstring = two.IndexOf('%') < 0 ? string.Empty : two.Substring(two.IndexOf('%') + 1);
This will check if the string doesn't contain the key %.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.