【问题标题】:C# count ocurrences of several char in string using regex.Matches.count onceC# 使用 regex.Matches.count 计算字符串中多个字符的出现次数
【发布时间】:2013-12-02 08:25:33
【问题描述】:

有一个类似的字符串:

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;

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

【问题讨论】:

  • 你为什么把“高效”和“正则表达式”放在同一个句子里? :)
  • 是的,你是对的,我应该写,尝试制作更高效的正则表达式代码?
  • 嗯,你可以根据你使用的编程语言使用内置的字符串搜索库。
  • 我用的是c#,也许用case语句做一个for循环就够了

标签: c# regex


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 2023-02-04
    • 2011-04-21
    • 1970-01-01
    • 2014-04-24
    • 2017-10-09
    • 2010-11-12
    相关资源
    最近更新 更多