Reputation: 11
I'm looking for a way to count only certain numbers, and decrease by 1
if you cannot find the number when provided with a string.
For example,
string test = "987652349";
How can I count how many 9
s are in the string? And if no 9
s, count 8
instead? If not, count 7
? Etc.
I have a complicated if
loop that isn't too pleasing to look at. The numbers always start from 9
and looks for that until 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;
}
etc.
Upvotes: 0
Views: 122
Reputation: 469
Use while loop:
char c = '9';
while (c >= '1')
{
if (test.Contains(c))
{
count = test.Count(x => x == c);
// blah blah;
break;
}
c--;
}
Upvotes: 0
Reputation: 109
You can use recursion.
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;
}
and then call it like
var count = Counter(test,9);
of course, you need to modify it if you want to now which nr there is x nr of.
Upvotes: 0
Reputation: 186668
Single pass solution
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
Upvotes: 5