问题
I have strings that have a directory in the following format:
C://hello//world
How would i extract everything after the last / character (world)?
回答1:
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.
回答2:
using System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();
回答3:
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.
回答4:
Try this:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
回答5:
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;
来源:https://stackoverflow.com/questions/15857589/get-contents-after-last-slash