删除字符串的特定部分

时间:2012-08-06 12:13:40

标签: c# string

我有一些类似于FFS\D46_24\43_2的字符串我想在第一个反斜杠和最后一个下划线之间返回文本。在上面的示例中,我想获得D46_24\43

我尝试了下面的代码,但它引发了超出范围的争论:

    public string GetTestName(string text)
    {
        return text.Remove(
            text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase)
            ,
            text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase)
            );
    }

7 个答案:

答案 0 :(得分:8)

第二个参数是计数,而不是结束索引。此外,隔离部分字符串的正确方法是Substring而不是Remove。所以你必须把它写成

var start = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase);
var end = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase);

// no error checking: assumes both indexes are positive
return text.Substring(start + 1, end - start - 1);

答案 1 :(得分:3)

第二个参数不是结束索引 - 它应该是要删除的字符数。

请参阅the documentation了解此次重载。

int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase);
int endIndex = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase)

return text.Remove(startIndex, endIndex - startIndex);

答案 2 :(得分:1)

这是正则表达式的工作。

var regex = new Regex( @"\\(.+)_" );
var match = regex.Match( @"FFS\D46_24\43_2" );

if( match.Success )
{
    // you can loop through the captured groups to see what you've captured
    foreach( Group group in match.Groups )
    {
        Console.WriteLine( group.Value );
    }
}

答案 3 :(得分:1)

使用正则表达式:

Match re = Regex.Match("FFS\D46_24\43_2", @"(?<=\\)(.+)(?=_)");
if (re.Success)
{
    //todo
}

答案 4 :(得分:0)

您应该使用Substring而不是Remove。 试试这个:

public static string GetTestName(string text)
    {
        int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase);
        int endIndex = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase);

        if (startIndex < 0 || endIndex < 0)
            throw new ArgumentException("Invalid string: no \\ or _ found in it.");

        if (startIndex == text.Length - 1)
            throw new ArgumentException("Invalid string: the first \\ is at the end of it.");

        return text.Substring(startIndex + 1, 
                              endIndex - startIndex - 1);
    }

答案 5 :(得分:0)

string text = @"FFS\D46_24\43_2";
int startIndex = text.IndexOf("\\", StringComparison.InvariantCultureIgnoreCase),
    lastIndex  = text.LastIndexOf("_", StringComparison.InvariantCultureIgnoreCase);

return text.Substring(startIndex + 1, lastIndex-startIndex-1);

答案 6 :(得分:0)

string.Remove()的第二个参数是要删除的元素数,而不是要删除的上层索引。

请参阅http://msdn.microsoft.com/en-us/library/d8d7z2kk.aspx

编辑:正如其他人所说,你想使用Substring(),而不是Remove()

请参阅http://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.71%29.aspx