Search code examples
c#string-parsing

Get contents after last slash


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

C://hello//world

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


Solution

  • 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.