【问题标题】:Is there a better way to count certain numbers in a string?有没有更好的方法来计算字符串中的某些数字?
【发布时间】:2021-11-23 08:40:46
【问题描述】:

我正在寻找一种方法来计算某些数字,如果在提供字符串时找不到数字,则减少1。 p>

例如,

string test = "987652349";

如何计算字符串中有多少个9s?如果没有9s,则改为计数8?如果没有,算7?等等。

我有一个复杂 if 循环,看起来不太好看。数字总是从9 开始,一直到1

for each c in test
    if (test.Contains("9")){
      count = test.Where(x => x == '9').Count();
      blah blah;
    }

    else if (test.Contains("8")){
      count = test.Where(x => x == '8').Count();
      blah blah;
    }

等等

【问题讨论】:

  • 字符总是全是数字吗? count = test.Count(x => x == test.Max())?
  • 请用有效的 C# 重写你的“例子”。
  • 虽然 LINQ 解决方案是最好的,但您的循环最好写成从 '9''0' 并在它包含在 test 中时中断。事实上,正如所写的那样,您的 for each (sic) 循环没有任何用处,因为您从未在体内引用 c
  • @JoachimIsaksson 也许两行? var maxdigit = test.Max(); var countmaxdigit = test.Count(ch => ch == maxdigit);
  • @NetMage 是的,linq 解决方案并不完全是最优的,因为它为每个字符运行 test.Max(),分两步执行肯定更好。

标签: c# algorithm


【解决方案1】:

单程解决方案

char charToCount = '0';
int count = 0;

foreach (char c in test) 
  if (c == charToCount)
    count += 1;
  else if (c > charToCount && c <= '9') {
    // if we have a better candidate
    charToCount = c;
    count = 1;
  }

blah blah

【讨论】:

  • 好主意! (不过,我将变量命名为 charToCount)。同样在for each,不应该是char c 而不是int c? (我喜欢var的原因之一。)
  • 我无法抗拒 LINQ / 单行版本:var countmaxdigit = test.Aggregate((charToCount: '0', count: 0), (maxch_count, ch) =&gt; (ch == maxch_count.charToCount) ? (ch, maxch_count.count+1) : (ch &gt; maxch_count.charToCount) ? (ch, 1) : maxch_count).count; BTW, ++count;?
【解决方案2】:

你可以使用递归。

    private int Counter(string[] numbers, int countFrom)
    {
            if (countFrom == 0)
                return 0;

            var nrOfMyNr = numbers.Where(x => x == countFrom.ToString()).Count();

            if (nrOfMyNr == 0)
            {
                countFrom -= 1;
                return Counter(numbers, countFrom);
            }

            else
                return nrOfMyNr;
    }

然后像这样称呼它

    var count = Counter(test,9);

当然,如果你想现在哪个nr有x nr,你需要修改它。

【讨论】:

  • 您可能想在递归中对 Counter 的返回值做一些事情,也许将其返回或分配给 nrOfMyNr?
  • 对不起,你说得对。我已经编辑了
【解决方案3】:

使用while循环:

        char c = '9';
        while (c >= '1')
        {
            if (test.Contains(c))
            {
                count = test.Count(x => x == c);
                // blah blah;
                break;
            }

            c--;
        }

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多