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

Time:10-02

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 9s are in the string? And if no 9s, 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.

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

A one pass solution using a Dictionary<int, int> in addition to a sort... Also this counts all the digits if needed.

string test = "987652349";
Dictionary<int, int> dictionary = new Dictionary<int, int>();
int targetNumber;
foreach (char c in test.ToArray()) {
  if (int.TryParse(c.ToString(), out targetNumber)) {
    if (dictionary.ContainsKey(targetNumber)) {
      dictionary[targetNumber]  ;
    }
    else {
      dictionary.Add(targetNumber, 1);
    }
  }
}
var Ordered = from pair in dictionary
              orderby pair.Key descending
              select pair; 
MessageBox.Show("Highest digit count: Number: "   Ordered.ElementAt(0).Key   " Count: "  
                                                    Ordered.ElementAt(0).Value);
  •  Tags:  
  • c#
  • Related