title: Count number of tokens matching a pattern in a string
body: <p>A method to count number of tokens matching a pattern in a string.</p>
  
  <p>token is a "$" followed by "$$", there can be any number of characters between "$" and "$$".</p>
  
  <p>Eg: <code>"$123$$, $ab$$, $qqwe123$$</code></p>
  
  <p>input string could be <code>"$122$$dddd$1aasds$$"</code>.</p>
  
  <p>The output of the method should be 2 for the above string.</p>
  
  <p>Programming Language could C# or C++.</p>
  
  <p>here is the code I came up with but trying to find the best way possible:</p>
  
  <pre><code>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 &lt; s.Length; i++)
              {
                  if (s[i] == '$' &amp;&amp; !foundOneDollar)
                  {
                      foundOneDollar = true;
                      continue;
                  }
  
                  if (foundOneDollar)
                  {
                      if (s[i] == '$' &amp;&amp; !foundSecondDollar)
                      {
                          foundSecondDollar = true;
                          continue;
                      }
                  }
  
                  if (foundSecondDollar)
                  {
                      if (s[i] == '$')
                      {
                          tokenCount++;
                      }  
                      foundSecondDollar = false;
                  }
              }
              Console.WriteLine(tokenCount);
              return tokenCount;
          }
  </code></pre>