2013-03-23 90 views
1

计算匹配字符串中的模式的令牌数的方法。计算匹配字符串中的模式的令牌数

标记是一个“$”后面跟着“$$”,“$”和“$$”之间可以有任意数量的字符。

如:"$123$$, $ab$$, $qqwe123$$

输入字符串可以为"$122$$dddd$1aasds$$"

对于上面的字符串,该方法的输出应为2。

编程语言可以C#或C++。

这里是我想出了,但试图找到最好的方式代码:

static int CalculateTokenCount() 
     { 
      string s = "$ab$$ask$$$$123$$"; 
      int tokenCount = 0; 
      bool foundOneDollar = false; 
      bool foundSecondDollar = false; 

      if (string.IsNullOrEmpty(s)) 
      { 
       return tokenCount; 
      } 
      for (int i = 0, x = 0; i < s.Length; i++) 
      { 
       if (s[i] == '$' && !foundOneDollar) 
       { 
        foundOneDollar = true; 
        continue; 
       } 

       if (foundOneDollar) 
       { 
        if (s[i] == '$' && !foundSecondDollar) 
        { 
         foundSecondDollar = true; 
         continue; 
        } 
       } 

       if (foundSecondDollar) 
       { 
        if (s[i] == '$') 
        { 
         tokenCount++; 
        } 
        foundSecondDollar = false; 
       } 
      } 
      Console.WriteLine(tokenCount); 
      return tokenCount; 
     } 
+5

http://whathaveyoutried.com先让你的努力来获取计数。这不是Stackoverflow的_real问题,请阅读[常见问题]和[问]几次.. – 2013-03-23 13:32:52

+0

优秀的问题。你有我的前进来解决它 – user93353 2013-03-23 13:57:04

回答

0

您可以使用下面的正则表达式

\$.*?\$\$ 

该检测任何之间的字符数,甚至是零个字符。如果您至少需要一个字符,请将*替换为+

正如@astander已经说过,比赛用Regex.Matches

string input = "$122$$dddd$1aasds$$"; 
string pattern = @"\$.*?\$\$"; 
Regex rgx = new Regex(pattern); 
MatchCollection matches = rgx.Matches(input); 
int count = matches.Count();