【问题标题】:Return how many numbers a number contains返回一个数字包含多少个数字
【发布时间】:2023-01-24 16:04:43
【问题描述】:

我有一串数字,我想计算该字符串有多少个数字。

例子:

111222
1002345
000000

预期输出:

111222 2
1002345 6
000000 1

我使用以下代码实现了这一点:

        private static int Counter(string ID)
    {
        char[] numbers = new char[]{'0','1','2','3','4','5','6','7','8','9'};
        List<int> listofmatched = new List<int>();
        var split = ID.ToArray();
        foreach (var num in split)
        {
            if (numbers.Contains(num))
            {
                if (listofmatched.Contains(num))
                {
                    continue;
                }
                else
                {
                    listofmatched.Add(num);
                }
            }
        }
        return listofmatched.Count;
    }

有什么办法可以改进上面的代码吗?我觉得有不必要的循环

【问题讨论】:

    标签: c# loops numbers


    【解决方案1】:

    不知道它是否符合您对“改进”的定义,但您可以这样做:

    str.Where(x => char.IsDigit(x)).GroupBy(x => x).Count();
    

    在这里查看:

    https://dotnetfiddle.net/t5OW6T

    【讨论】:

      【解决方案2】:

      您可以将数字添加到 HashSet,然后返回其大小

      static int Counter(string ID)
      {
          var hs = new HashSet<char>();
          foreach (var c in ID)
              hs.Add(c);
          return hs.Count;
      }
      

      【讨论】:

        【解决方案3】:

        如果你想使用快捷方式,你可以像这样使用字典:

        def calculate_different_in_string(num):
            d = {}
            while num > 0:
               d[num % 10 ] = 1
               d /= 10
        return len(d)
        

        【讨论】:

          猜你喜欢
          • 2014-12-16
          • 1970-01-01
          • 2016-04-11
          • 2013-08-11
          • 1970-01-01
          • 2014-10-25
          • 2021-09-12
          • 1970-01-01
          • 2010-12-28
          相关资源
          最近更新 更多