繁体   English   中英

如何从这个字符串中提取子字符串?

[英]How to extract substring from this string?

我试图在URL的末尾提取字符串。 例:

C:\this\that\ExtractThisString.exe
             ^^^^^^^^^^^^^^^^^^^^^

我试图从该字符串中获取ExtractThisString.exe ,但它有未知数量的\\ 我希望它基本上抓住URL并列出最后的内容。

使用System.IO.Path类的帮助方法。 在你的情况下:

string fileName = Path.GetFileName(@"C:\this\that\ExtractThisString.exe");

只是为了好玩,如果你必须自己创建,你应该开始搜索最后一个Path.DirectorySeparatorChar的索引。 如果那不是字符串中的最后一个字符 ,那么您可以使用String.Substring来提取该索引之后的所有文本。

要查找指定字符使用的最后一次出现

int pos = yourString.LastIndexOf(@"\");

然后提取子字符串

string lastPart = yourString.Substring(pos+1);

编辑我在15个月后回顾这个答案,因为我真的错过了问题中的一个关键点。 OP正在尝试提取文件名,而不仅仅是查找给定字符的最后一次出现。 因此,虽然我的答案在技术上是正确的,但它并不是最好的,因为.NET框架有一个专门的类来处理文件名和路径。 这个类叫做Path ,你可以找到一个简单而有效的方法来使用Path.GetFileName来实现你的结果,如@Adriano的答案所述。

我还要强调一点,使用Path类中的方法可以获得代码可移植性,因为当不同的操作系统使用不同的目录分隔符char时,类会处理这种情况。

尝试这个

var str = @"C:\this\that\ExtractThisString.exe";
var filename = str.Substring(str.LastIndexOf("\\")+1);

为所有事做一次......

public static string FileAndExtension(this string aFilePath) {
 return aFilePath.Substring(aFilePath.LastIndexOf("\\") + 1);
}

"C:\\\\this\\\\that\\\\ExtractThisString.exe".FileAndExtension()

要么

public static string EverythingAfterLast(this string aString, string aSeperator) {
 return aString.Substring(aString.LastIndexOf(aSeperator) + 1);
}

"C:\\\\this\\\\that\\\\ExtractThisString.exe".EverythingAfterLast("\\\\")

string path = @"c:\this\that\extractthisstring.exe";
Console.WriteLine(path.Split('\\').Reverse().First());

我使用System.IO找到并使用这种优雅的方式

string file1 = Path.GetFileName(@"C:\\this\\that\\ExtractThisString.exe");

或者如果你想没有扩展名

string file2 = Path.GetFileNameWithoutExtension(@"C:\\this\\that\\ExtractThisString.exe");

或只是扩展名

string ext = Path.GetExtension(@"C:\\this\\that\\ExtractThisString.exe");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM