C#、. NET 3.5

这对我来说很难闻,但我想不出另一种方法。

给定一个格式为“Joe Smith(jsmith)”(无引号)的字符串,我只想解析括号中的“jsmith”字符串。我想出了这个:

private static string DecipherUserName( string user )
{
    if( !user.Contains( "(" ) )
        return user;

    int start = user.IndexOf( "(" );

    return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
}

除了我对RegEx的(不健康的)厌恶之外,还有没有更简单的方法来解析子字符串?

编辑:
为了明确起见,要解析的字符串将始终为:“Joe Smith(jsmith)”(无引号)。

最佳答案

您不需要第一次替换,因为您可以在“(”位置加1。

private static string DecipherUserName (string user) {
    int start = user.IndexOf( "(" );
    if (start == -1)
        return user;
    return user.Substring (start+1).Replace( ")", string.Empty );
}

关于c# - 用C#解析一个字符串;有没有更清洁的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/728018/

10-11 22:34
查看更多