Reputation: 25048
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?
Upvotes: 0
Views: 227
Reputation: 19416
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.
Upvotes: 1