删除名称前的字符串中的所有字符
问题描述:
如何删除字符串中的所有字符,直到匹配某个名称?例如,我有以下字符串:删除名称前的字符串中的所有字符
"C:\\Installer\\Installer\\bin\\Debug\\App_Data\\Mono\\etc\\mono\\2.0\\machine.config"
如何字符串“App_Data
”之前删除所有字符?
答
var str = @"C:\Installer\Installer\bin\Debug\App_Data\Mono\etc\mono\2.0\machine.config";
var result = str.Substring(str.IndexOf("App_Data"));
Console.WriteLine(result);
打印:
App_Data\Mono\etc\mono\2.0\machine.config
好了,这样做的那种花哨的方式是尝试使用独立于平台的类Path,其目的是处理文件和目录路径的操作。在您简单的例子第一个解决方案是在多种因素的更好,并考虑下一个仅作为一个例子:
var result = str.Split(Path.DirectorySeparatorChar)
.SkipWhile(directory => directory != "App_Data")
.Aggregate((path, directory) => Path.Combine(path, directory));
Console.WriteLine(result); // will print the same
答
或者作为扩展方法来实现:
public static class Extension
{
public static string TrimBefore(this string me, string expression)
{
int index = me.IndexOf(expression);
if (index < 0)
return null;
else
return me.Substring(index);
}
}
,并使用它像:
string trimmed = "i want to talk about programming".TrimBefore("talk");