我有一些字符串,其格式为以下目录:
C://hello//world
如何提取最后一个/
字符之后的所有内容(world
)?
我有一些字符串,其格式为以下目录:
C://hello//world
如何提取最后一个/
字符之后的所有内容(world
)?
string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"
LastIndexOf
方法与 IndexOf
方法类似,但是从字符串结尾开始搜索。
使用 System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();
有一个用于处理路径的静态类,名为Path
。
您可以使用Path.GetFileName
获取完整的文件名。
或者
您可以使用Path.GetFileNameWithoutExtension
获取没有扩展名的文件名。
Path.GetFileName("C://hello//world")
将返回world
。 - Martin Schneider试试这个:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
System.IO
命名空间,因为您可能想要使用它。这里有 DirectoryInfo 和 FileInfo,可能会对您有帮助。具体来说,DirectoryInfo 的 Name 属性 可能会有用。var directoryName = new DirectoryInfo(path).Name;
Console.WriteLine(path[pos..]);
有关详细信息,请参见:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges - Kyle