简体   繁体   中英

Is there a better way to count certain numbers in a string?

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.

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

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.

Use while loop:

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

            c--;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM