Get contents after last slash

陌路散爱 提交于 2019-12-09 14:19:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!