Home > Net >  Return how many numbers a number contains
Return how many numbers a number contains

Time:01-24

I have a string of number and i want to count how many numbers the string has.

Example:

111222
1002345
000000

Expected output:

111222 2
1002345 6
000000 1

I have achieved this using the following code:

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

Is there any way to improve the code above? I feel like there's unnecessary loops

CodePudding user response:

Don't know if it fits your defintion of "improvement", but you could do it like this:

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

See it here:

https://dotnetfiddle.net/t5OW6T

Edit:

As noticed in the comments, you could also use Distinct isntead of GroupBy(x => x).

GroupBy(x => x) can be useful if you want to know which digit occurs how often in the string, this can be done like this:

str.Where(x => char.IsDigit(x)).GroupBy(x => x).Select(x => (x.Key, x.Count()))

Where instead of calling Count on the "whole" grouping result, you evaluate the Count for each individual group of the grouping result.

You may find an example here:

https://dotnetfiddle.net/D60ygZ

CodePudding user response:

You can add the digits to HashSet, and then return its size

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

CodePudding user response:

if you want to shortcut you can use a dictionary instead like this:

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