Reputation: 196861
I have a string that looks like this
/root/test/test2/tesstset-werew-1
And I want to parse the word after the last /
. So in this example, I want to grab the word tesstset-werew-1
. What is the best way of doing this in C#? Should I split the string into an array or is there some built in function for this?
Upvotes: 0
Views: 461
Reputation: 161012
If this is a path, which seems to be the case in your example you can use Path.GetFileName()
:
string fileName = Path.GetFileName("/root/test/test2/tesstset-werew-1");
Upvotes: 3
Reputation: 42450
Splitting into an array is probably the easiest way to do it. The other would be regex
something like this would work:
string[] segments = yourString.Split('/');
try
{
lastSegment = segments[segments.length - 1];
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Your original string does not have slashes");
}
You would want to put a check that segments[] has elements before the second statement.
Upvotes: 1
Reputation: 86892
string mystring = "/root/test/test2/tesstset-werew-1";
var mysplitstring = mystring.split("/");
string lastword = mysplitstring[mysplitstring.length - 1];
Upvotes: 3