Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#使用regex.Matches.count一次性计算字符串中几个字符的出现次数_C#_Regex - Fatal编程技术网

C#使用regex.Matches.count一次性计算字符串中几个字符的出现次数

C#使用regex.Matches.count一次性计算字符串中几个字符的出现次数,c#,regex,C#,Regex,具有类似于: 0x1TTTT10TT1Tx01Tx1001xxx100T0TxT1T1TxTxTxx0TT0000000x0xTxT1Tx0T0x10x1 我想得到: 0 appears 20 1 appears 12 x appears 17 T appears 21 如果我使用 int zero = Regex.Matches(input, "0").Count; int one = Regex.Matches(input, "1").Coun

具有类似于:

0x1TTTT10TT1Tx01Tx1001xxx100T0TxT1T1TxTxTxx0TT0000000x0xTxT1Tx0T0x10x1
我想得到:

 0 appears 20
 1 appears 12 
 x appears 17
 T appears 21
如果我使用

        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;

如何使用更有效的方法使用正则表达式实现相同的结果

这并不是正则表达式的真正目的。我建议在字符上使用循环,如下所示:

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;
    }
}

不幸的是,效率最高的通常不是最简洁的。

为什么你把“效率”和“正则表达式”放在同一句话里?:)是的,你是对的,我应该写,试着制作更高效的正则表达式代码?好吧,你可以使用内置的字符串搜索库,这取决于你使用的编程语言。我使用的是c#,也许用case语句做for循环会更有效。请看这里:这里: