0

Having a string like:

0x1TTTT10TT1Tx01Tx1001xxx100T0TxT1T1TxTxTxx0TT0000000x0xTxT1Tx0T0x10x1

I want to get:

 0 appears 20
 1 appears 12 
 x appears 17
 T appears 21

If I use

        int zero = Regex.Matches(input, "0").Count;
        int one  = Regex.Matches(input, "1").Count;
        int x    = Regex.Matches(input, "x").Count;
        int T    = Regex.Matches(input, "T").Count;

How to accomplish same result using more efficient approach using Regex?

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • Why did you put "efficient" and "regex" in the same sentence? :) – Blue Ice Nov 18 '13 at 23:57
  • Yes you are right, I should have written, try to make more efficient regex code? – edgarmtze Nov 18 '13 at 23:58
  • Well, you could use built-in string searching libraries depending on which programming language you are using. – Blue Ice Nov 19 '13 at 00:02
  • I am using c#, maybe doing a for loop with case statements will be enough – edgarmtze Nov 19 '13 at 00:02
  • Try looking here: http://stackoverflow.com/questions/10391481/number-of-occurrences-of-a-character-in-a-string and here: http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string-c?lq=1 – Blue Ice Nov 19 '13 at 00:04

1 Answers1

1

This is not really the real purpose of Regular Expressions. I would instead advise the use of a loop over the characters, like the following:

int zeroCount = 0;
int oneCount = 0;
int xCount = 0;
int tCount = 0;
foreach(var ch in input)
{
    switch(ch)
    {
        case '0':
            zeroCount++;
            break;
        case '1':
            oneCount++;
            break;
        case 'x':
            xCount++;
            break;
        case 'T':
            tCount++;
            break;
    }
}

Unfortunately the most efficient isn't usually the most concise.

Lukazoid
  • 19,016
  • 3
  • 62
  • 85