在最后一次斜杠后获取内容

我的字符串具有以下格式的目录:

C:// //你好世界

如何在最后一个/角色(世界)之后提取所有内容?

string path = "C://hello//world"; int pos = path.LastIndexOf("/") + 1; Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world" 

LastIndexOf方法与IndexOf相同,但是从字符串的末尾开始。

有一个静态类用于处理名为Path Paths。

您可以使用Path.GetFileName获取完整的文件名。

要么

您可以使用Path.GetFileNameWithoutExtension获取不带扩展名的文件名。

using System.Linq;

 var s = "C://hello//world"; var last = s.Split('/').Last(); 

试试这个:

 string worldWithPath = "C://hello//world"; string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1); 

我建议查看System.IO命名空间,因为您似乎可能想要使用它。 这里也有可能有用的DirectoryInfo和FileInfo。 特别是DirectoryInfo的Name属性

 var directoryName = new DirectoryInfo(path).Name;