我想计算一行中使用了多少个数字(仅0,1,2,3 )和字母( a,b,c,d )我正在检查 - 它们是混合的,例如: 3b1c1c1a1a0b1a1d3d0a3c 。我怎么算这个?
答案 0 :(得分:5)
int numbers = 0;
int letters = 0;
foreach(char a in myString)
{
if (Char.IsDigit(a))
numbers ++;
else if (Char.IsLetter(a)){
letters ++;
}
答案 1 :(得分:1)
如果需要重新使用这些表达式,您还可以使用预定义的Linq表达式:
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();
答案 2 :(得分:0)
有一种方法可以做到这一点:
int count = myString.ToCharArray().Where(c => Char.IsLetterOrDigit(c)).Count();
如果你想将它们分开:
int letterCount = myString.ToCharArray().Where(c => Char.IsLetter(c)).Count();
int numberCount = myString.ToCharArray().Where(c => Char.IsDigit(c)).Count();
如果您想根据数字过滤它们:
List<char> searchFor = new List<char>() { '0', '1', '2', '3' };
int numberCount = myString.ToCharArray().Where(c => searchFor.Contains(c)).Count();
答案 3 :(得分:0)
您可以使用ASCII代码使其正常工作
for(int i = 0 ; i < str.Length ; i++){
int asciicode = (int)str[i];
if(asciicode >= 48 && asciicode <= 57)
number++;
else
alphabet++;
}
答案 4 :(得分:0)
这是一个查找字符数&#34; 1&#34;:
的示例 string input = "3b1c1c1a1a0b1a1d3d0a3c";
int count = input.ToArray().Count(i => i == '1');
答案 5 :(得分:0)
以下符合您的要求:
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;