I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?
7 Answers
Try this:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
or
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
to split, the latter will remove the empty string.
Adding .Last() will get you the last item.
e.g.
toSplit.Split('/').Last();
1 Comment
Jesus Ramos
SplitOptions.RemoveEmptyEntries :P or something like that I forget the exact name, to get rid of the empty you would get because of the first /
Use .Split().
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
This site have quite a few examples of splitting strings in C#. It's worth a read.
Comments
Using .Split and a little bit of LINQ, you could do the following
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
Otherwise you could do
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts
1 Comment
Binary Worrier
Possibly
string desiredValue = str.Substring(str.LastIndexOf("/")+1); because you don't want the seperator?