leora
leora

Reputation: 196861

How can I split the last instance of a character in a C# string?

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

Answers (5)

Lucifer
Lucifer

Reputation: 29670

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

Upvotes: 0

BrokenGlass
BrokenGlass

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

fardjad
fardjad

Reputation: 20424

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

Upvotes: 2

Ayush
Ayush

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

John Hartsock
John Hartsock

Reputation: 86892

The Split() method

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

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

string lastword = mysplitstring[mysplitstring.length - 1];

Upvotes: 3

Related Questions