获取最后一个斜杠后面的内容

53

我有一些字符串,其格式为以下目录:

C://hello//world

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

5个回答

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

LastIndexOf 方法与 IndexOf 方法类似,但是从字符串结尾开始搜索。


3
自C# 8.0起,您还可以使用范围运算符。Console.WriteLine(path[pos..]);有关详细信息,请参见:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges - Kyle
2
注意到当字符串中没有斜杠时,它是如何工作的是一件好事。它返回整个字符串,这通常是正确的。此外,Substring方法不需要第二个参数,它会自动返回字符串的结尾处的所有内容。 - Palec

52

使用 System.Linq;

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

16

1
我曾经考虑过这个问题,但是注意到原帖似乎并没有专注于文件,而是目录。 - Justin Pihony
注意:如果文件名包含冒号“:”,则此方法无法正常工作,例如//depot/some:file.ext。GetFileName仅返回file.ext,这可能不是您所期望的结果。这在Windows系统上不是有效的路径,但OP没有指定操作系统。 - pangabiMC
@JustinPihony,无论是文件还是目录都没关系。Path.GetFileName("C://hello//world")将返回world - Martin Schneider

11

试试这个:

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

2
这是与Simon Whitehead(https://dev59.com/3WUo5IYBdhLWcg3wrg9D#15857606)已发布的相同解决方案,除了在“Substring”方法调用中明确给定长度。 - abto
这是更聪明的解决方案,而不是@abto。 - Lali

6
我建议您查看 System.IO 命名空间,因为您可能想要使用它。这里有 DirectoryInfo 和 FileInfo,可能会对您有帮助。具体来说,DirectoryInfo 的 Name 属性 可能会有用。
var directoryName = new DirectoryInfo(path).Name;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接