I have strings that have a directory in the following format:
C://hello//world
How would I extract everything after the last /
character (world
)?
I have strings that have a directory in the following format:
C://hello//world
How would I extract everything after the last /
character (world
)?
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.
using System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();
There is a static class for working with Paths called Path
.
You can get the full Filename with Path.GetFileName
.
or
You can get the Filename without Extension with Path.GetFileNameWithoutExtension
.
Try this:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
I would suggest looking at the System.IO
namespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property
var directoryName = new DirectoryInfo(path).Name;