删除最后一个字符串\

时间:2014-06-07 04:28:12

标签: c#

我正在尝试使用lastindexof删除\之后的最后一个字符串,但我无法知道如何执行此操作。

这是我要解析的字符串的示例:

string path = "C:\Program Files\Google\";
string path2 = "C:\Program Files\Google\Chrome\";

我想删除路径中的Google或Chrome,但如果我使用lastindexof'\'则无效。那么在c#中执行此操作的最快或最标准的方法是什么。

编辑:这只是一个例子,我不是为路径工作。

4 个答案:

答案 0 :(得分:1)

我建议你不要这样做 - 使用Directory.GetParent来获取父目录:

string path2 = @"C:\Program Files\Google\Chrome\";
var parentFolder = Directory.GetParent(Path.GetDirectoryName(path2)).FullName;

答案 1 :(得分:1)

一种标准方法是使用System.IO.Directory.GetParent。但请注意,如果路径具有尾随分隔符,则需要应用GetParent两次。见http://msdn.microsoft.com/en-us/library/system.io.directory.getparent(v=vs.110).aspx

using System.IO;

if (path.EndsWith("\\"))
{
    path = Directory.GetParent(Directory.GetParent(path).FullName).FullName;
}
else
{
    path = Directory.GetParent(path).FullName;
}

更新:对于更一般的基于字符串的方法:

var a = @"a\b\c\";
var b = a.LastIndexOf("\\", a.Length-2);
var c = a.Substring(0, b);

LastIndexOf允许使用从中向后看的起始索引。见http://msdn.microsoft.com/en-us/library/system.string.lastindexof(v=vs.110).aspx

答案 2 :(得分:0)

确定。这是你的答案。

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);

答案 3 :(得分:0)

TrimEnd('\\')你的字符串,然后使用最后一个索引。

相关问题