Get contents after last slash

john cs picture john cs · Apr 7, 2013 · Viewed 57.5k times · Source

I have strings that have a directory in the following format:

C://hello//world

How would I extract everything after the last / character (world)?

Answer

Simon Whitehead picture Simon Whitehead · Apr 7, 2013
string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"

The LastIndexOf method performs the same as IndexOf.. but from the end of the string.