简体   繁体   中英

C# Counting numbers & letters

I want to count how many numbers ( only 0,1,2,3 ) and letters ( a,b,c,d ) were used in a line that I'm checking - they are mixed, for example: 3b1c1c1a1a0b1a1d3d0a3c . How can I count that?

int numbers = 0;
int letters = 0;

foreach(char a in myString)
{
  if (Char.IsDigit(a))
    numbers ++;
  else if (Char.IsLetter(a)){
    letters ++;
}

You could also use predefined Linq expressions if these need to be re-used:

var characterList = "234234abce".ToCharArray();
var validCharacters = "0123abcd".ToCharArray();

Func<char, bool> ValidLetter = delegate(char c){
    return Char.IsLetter(c) && validCharacters.Contains(c);
};
Func<char, bool> ValidNumber = delegate(char c){
    return Char.IsDigit(c) && validCharacters.Contains(c);
};

var letterCount = characterList.Where(c => ValidLetter(c)).Count();
var numberCount = characterList.Where(c => ValidNumber(c)).Count();

There's a method for doing that:

int count = myString.ToCharArray().Where(c => Char.IsLetterOrDigit(c)).Count();

If you want to split them out then:

int letterCount = myString.ToCharArray().Where(c => Char.IsLetter(c)).Count();
int numberCount = myString.ToCharArray().Where(c => Char.IsDigit(c)).Count();

If you want to filter them based on the numbers:

 List<char> searchFor = new List<char>() { '0', '1', '2', '3' };
 int numberCount = myString.ToCharArray().Where(c => searchFor.Contains(c)).Count();

You can use the ASCII code to get it work

             for(int i = 0 ; i < str.Length ; i++){
             int asciicode = (int)str[i];
             if(asciicode >= 48 && asciicode <= 57)
                        number++;
             else
                      alphabet++;                 
      } 

This is an example to find the count of character "1":

        string input = "3b1c1c1a1a0b1a1d3d0a3c";
        int count = input.ToArray().Count(i => i == '1');

Below meets your requirements:

string acceptedChars = "0123abcd";

var res = "3b1c1c1a1a0b1a1d3d0a3c".ToCharArray()
    .Where(x => acceptedChars.Contains(x))
    .GroupBy(x => char.IsDigit(x))
    .Select(g => new{ isDigit = g.Key, count = g.Count() } );

var digitsCount = res.Single(r => r.isDigit == true).count;
var lettersCount = res.Single(r => r.isDigit == false).count;

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