c++当给定一个字符串,编写一个函数来计算其中包含的字母数(不区分大小写)。
作者:野牛程序员:2023-08-11 20:20:38 C++阅读 2631
c++当给定一个字符串,编写一个函数来计算其中包含的字母数(不区分大小写)。
#include <iostream> #include <string> int countLetters(const std::string& str) { int count = 0; for (char c : str) { if (isalpha(c)) { count++; } } return count; } int main() { std::string text = "Hello, World! 123"; int letterCount = countLetters(text); std::cout << "Number of letters: " << letterCount << std::endl; return 0; }
要实现计算给定字符串中包含的字母数(不区分大小写),可以按照以下方式编写函数,使用 ASCII 码进行比较。以下是使用 C++98 语法的示例代码:
#include <iostream> #include <string> int countLetters(const std::string &str) { int count = 0; for (std::string::size_type i = 0; i < str.length(); ++i) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) { count++; } } return count; } int main() { std::string input; std::cout << "请输入字符串: "; std::cin >> input; int result = countLetters(input); std::cout << "包含的字母数: " << result << std::endl; return 0; }
这个程序中,countLetters
函数遍历输入字符串中的每个字符,然后检查其 ASCII 码是否处于大写字母或小写字母的范围内,如果是,则将计数器加一。最后,将计数器的值返回。
请注意,此代码只计算了英文字母(不区分大小写),如果需要考虑其他字符,可能需要进行相应的修改。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
