I have a string of digits and I want to count how many unique digits the string contains.
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.
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: