0

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?

5 Answers 5

3

The Split() method

string mystring = "/root/test/test2/tesstset-werew-1";

var mysplitstring = mystring.split("/");

string lastword = mysplitstring[mysplitstring.length - 1];
Sign up to request clarification or add additional context in comments.

Comments

3

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");

Comments

2
yourString.Substring(yourString.LastIndexOf('/') + 1);

Comments

1

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.

Comments

0

You can run the for loop in reverse order till the / sign.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.