2013-03-23 85 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();