Count a specific letter in a string
本问题已经有最佳答案,请猛点这里访问。
新的C语言。我希望我的程序计算特定字母在字符串中出现的数量。
1 2 3 4 5 6 7 8 9 | public static int countLetters(string word, string countableLetter) { int count = 0; foreach (char c in word) { count++; } return count; } |
如果搜索准确的字符,则将第二个参数类型更改为
1 2 3 4 5 6 7 8 9 10 | public static int countLetters(string word, char countableLetter) { int count = 0; foreach (char c in word) { if(countableLetter == c) count++; } return count; } |
但您可以使用
1 | return word.Count(x => x == countableLetter); |
附加:
如果要查找任何字符串中包含的任何字符,则可以使用:
1 2 3 4 5 6 7 8 9 10 | public static int countLetters(string word, string countableLetters) { int count = 0; foreach (char c in word) { if(countableLetters.Contains(c)) count++; } return count; } |
或与LINQ:
1 | return word.Count(x => countableLetters.Contains(x)); |
您可以使用
1 | var count = word.Count(ch => ch == countableLetter); |
注意,您应该将