49

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

C://hello//world

我将如何提取最后一个/字符 ( world) 之后的所有内容?

4

5 回答 5

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

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

于 2013-04-07T00:39:05.283 回答
41

using System.Linq;

var s = "C://hello//world";
var last = s.Split('/').Last();
于 2016-02-12T19:51:07.290 回答
14

有一个用于处理路径的静态类,称为Path.

您可以使用Path.GetFileName.

或者

您可以使用Path.GetFileNameWithoutExtension.

于 2013-04-07T01:35:10.257 回答
10

试试这个:

string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
于 2017-01-14T13:57:13.020 回答
6

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

var directoryName = new DirectoryInfo(path).Name;
于 2013-04-07T01:07:43.533 回答