C# 删除后的最后一个字符串\
我正在尝试删除\使用lastindexof后的最后一个字符串,但我不知道如何执行此操作 这是我要分析的字符串的示例:C# 删除后的最后一个字符串\,c#,C#,我正在尝试删除\使用lastindexof后的最后一个字符串,但我不知道如何执行此操作 这是我要分析的字符串的示例: string path = "C:\Program Files\Google\"; string path2 = "C:\Program Files\Google\Chrome\"; 我想删除路径中的Google或Chrome,但如果我使用“\”的lastindexof,它将不起作用。那么,在c#中,最快或标准的方法是什么呢 编辑:这只是一个示例,我不使用path。我建议您根本
string path = "C:\Program Files\Google\";
string path2 = "C:\Program Files\Google\Chrome\";
我想删除路径中的Google或Chrome,但如果我使用“\”的lastindexof,它将不起作用。那么,在c#中,最快或标准的方法是什么呢
编辑:这只是一个示例,我不使用path。我建议您根本不要这样做-使用获取父目录:
string path2 = @"C:\Program Files\Google\Chrome\";
var parentFolder = Directory.GetParent(Path.GetDirectoryName(path2)).FullName;
一种标准方法是使用
System.IO.Directory.GetParent
。但是,请注意,如果路径有尾随分隔符,则需要应用GetParent
两次。看
更新:对于更通用的基于字符串的方法:
var a = @"a\b\c\";
var b = a.LastIndexOf("\\", a.Length-2);
var c = a.Substring(0, b);
LastIndexOf
允许使用起始索引,从该索引向后查看。请参见“确定”。这是你的答案
string path2 = @"C:\Program Files\Google\Chrome\";
int count = 0;
int i = 0;
for (i = path2.Length; i > 0; i--)
{
if (path2[i-1] == '\\')
{
count++;
if(count == 2) //Change the condition according to your requirement.
break; //For example if you want upto last third "\" then put 3 in the condition
}
}
path2 = path2.Substring(0, i);
TrimEnd('\\')
编辑字符串,然后使用最后一个索引。如果要处理文件路径,请使用System.IO
命名空间中的Path
类。例如,可能重复的函数I'm not working For path/directory我只需要删除最后一个字符串。所以我可以把它应用到其他事情上。讨论最后一个指数的时候肯定有十几个问题。。。这个应该关闭。如果是C:\
或C:\Program Files\Google\Chrome
,那会给你C:\Program Files\Google\Chrome
(至少对我来说是这样)…啊,真的-奇怪的行为-首先提取目录名修复了OP特别说他不处理路径。虽然信息是正确的,但它并没有回答他的问题。这部分内容是在我写完我的报告后编辑的answer@BrokenGlass-因此,修改或删除您的答案。OP明确表示他不使用路径。虽然信息是正确的,但并没有回答他的问题。在我给出答案后,问题被修改了。
string path2 = @"C:\Program Files\Google\Chrome\";
int count = 0;
int i = 0;
for (i = path2.Length; i > 0; i--)
{
if (path2[i-1] == '\\')
{
count++;
if(count == 2) //Change the condition according to your requirement.
break; //For example if you want upto last third "\" then put 3 in the condition
}
}
path2 = path2.Substring(0, i);