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

joh*_* cs 28 c# string-parsing

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

C:// //你好世界

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

Sim*_*ead 47

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

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

  • 从 C# 8.0 开始,您还可以使用范围运算符。```C# Console.WriteLine(path[pos..]); ``` 有关参考,请参阅:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges (3认同)
  • 值得注意的是,当字符串中没有斜杠时,它是如何工作的。它返回整个字符串,这通常是正确的。此外,Substring 方法不需要第二个参数,它会自动返回直到字符串末尾的所有内容。 (2认同)

Mat*_*kan 18

using System.Linq;

var s = "C://hello//world";
var last = s.Split('/').Last();
Run Code Online (Sandbox Code Playgroud)


Dus*_*gen 14

有一个用于处理Paths的静态类Path.

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

要么

您可以获取没有扩展名的文件名Path.GetFileNameWithoutExtension.


小智 7

试试这个:

string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
Run Code Online (Sandbox Code Playgroud)

  • 这与 Simon Whitehead (http://stackoverflow.com/a/15857606/2029849) 已经发布的解决方案相同,除了在 `Substring` 方法调用中明确给定的长度。 (2认同)

Jus*_*ony 6

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

var directoryName = new DirectoryInfo(path).Name;
Run Code Online (Sandbox Code Playgroud)