代码之家  ›  专栏  ›  技术社区  ›  Metro Smurf

用C解析字符串有更清晰的方法吗?

  •  5
  • Metro Smurf  · 技术社区  · 17 年前

    C.net,.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)”(无引号)。

    6 回复  |  直到 17 年前
        1
  •  9
  •   paxdiablo    17 年前

    您不需要第一个替换,因为您只需将1添加到“(”位置)。

    private static string DecipherUserName (string user) {           
        int start = user.IndexOf( "(" );
        if (start == -1)
            return user;
        return user.Substring (start+1).Replace( ")", string.Empty );
    }
    
        2
  •  20
  •   Shea    17 年前

    正则表达式非常有用,你可以省下很多心痛,咬着子弹学习它们。不是整个舍邦,只是基础。

    一个有效的regex是“\w+\(.*)\)”-jsmith将在match.groups[1]中。

    一个简单的方法是找到一个网站,让你输入一个regex和一些文本,然后吐出匹配…

        3
  •  5
  •   Daniel Brückner    17 年前

    有点像黑客…^ ^

    return user.Substring(user.IndexOf('(') + 1).TrimEnd(')');
    

    如果 user 不包含左括号, IndexOf() 收益率 -1 ,我们加一,得到零,然后 SubString() 返回整个字符串。 TrimEnd() 除非用户名以右括号结尾,否则无效。

    如果 用户 包含左括号, 索引() 返回其索引,我们通过添加一个来跳过左括号,并用 Substring() . 最后,我们用 三元() .

        4
  •  5
  •   Matthew Sposato    17 年前

    如果用户字符串的格式总是“joe smith(jsmith)”,那么应该是这样的。

    private static string DecipherUserName(string user)
    {
        string[] names = user.Split(new char[] {'(', ')'});
        return names.Length > 2 ? names[1] : user;
    }
    

    如果用户字符串总是“joe smith(jsmith)”,那么这将始终有效。

    private static string DecipherUserName(string user)
    {
        return "jsmith";
    }
    

    第二条仅用于幽默目的。

        5
  •  2
  •   Dillie-O    17 年前

    由于indexof函数将在值不存在时返回-1,因此可以执行稍微不同的操作…

    private static string DecipherUserName( string user )
    {           
       int start = user.IndexOf( "(" );
    
       if (start > -1)
       {
          return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
       }
       else
       {
          return user;
       }
    }
    
        6
  •  1
  •   MartinStettner    17 年前

    我会用

    int start=user.IndexOf('(');
    if (start != -1) {
      end = user.IndexOf(')', start);
      return user.Substring(start+1,end-start-1);
    } else
      return user;
    

    但这只是一个表面上的变化:在indexof中使用字符有点快,而且使用子字符串方法似乎更准确地表达了应该做的事情(如果您有多对括号,该方法更健壮…)

    这就是说, 丹尼尔L 的方法(使用 String.Split )可能更简单(但对格式错误的字符串处理不太好,必须构造字符串数组)。

    总之,我建议您克服对正则表达式的厌恶,因为这种情况正是它们的目的所在:-)…