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?

5
  • Why did you put "efficient" and "regex" in the same sentence? :) Commented Nov 18, 2013 at 23:57
  • Yes you are right, I should have written, try to make more efficient regex code? Commented Nov 18, 2013 at 23:58
  • Well, you could use built-in string searching libraries depending on which programming language you are using. Commented Nov 19, 2013 at 0:02
  • I am using c#, maybe doing a for loop with case statements will be enough Commented Nov 19, 2013 at 0:02
  • Try looking here: stackoverflow.com/questions/10391481/… and here: stackoverflow.com/questions/541954/… Commented Nov 19, 2013 at 0:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.