编写一个C++函数,统计一个字符串里英文字母个数
时间: 2024-03-21 12:42:21 浏览: 14
下面是一个简单的C++函数,可以统计一个字符串里英文字母的个数:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int countLetters(string str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (isalpha(str[i])) { // 判断是否为字母
count++;
}
}
return count;
}
int main() {
string str = "Hello, world!";
int letterCount = countLetters(str);
cout << "There are " << letterCount << " letters in the string." << endl;
return 0;
}
```
该函数接受一个字符串作为输入,并使用一个循环遍历字符串中的每个字符。对于每个字符,函数使用isalpha()函数判断它是否为字母,如果是,计数器加1。最后,函数返回字母的总数。在主函数中,我们可以将一个字符串传递给函数,然后输出字母的个数。
相关问题
c++ 编写程序输入一个以回车结束的字符串(小于80个字符)分别统计其中英文字母、数字、其他字符的个数
下面是一个简单的 C++ 程序,可以实现输入一个以回车结束的字符串,并统计其中英文字母、数字、其他字符的个数:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
const int MAX_LEN = 80;
char str[MAX_LEN];
cin.getline(str, MAX_LEN); // 读入字符串
int letter_cnt = 0, digit_cnt = 0, other_cnt = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) {
letter_cnt++;
} else if (isdigit(str[i])) {
digit_cnt++;
} else {
other_cnt++;
}
}
cout << "英文字母个数:" << letter_cnt << endl;
cout << "数字个数:" << digit_cnt << endl;
cout << "其他字符个数:" << other_cnt << endl;
return 0;
}
```
程序中使用 `cin.getline()` 函数读入字符串,`strlen()` 函数获取字符串长度,`isalpha()` 和 `isdigit()` 函数判断字符类型。最后输出统计结果。
用C++编写一个函数,统计一条英文句子中字母的个数,在主程序中实现输入输出。
好的,我明白了。以下是使用 C++ 编写的一个函数,可以统计一条英文句子中字母的个数:
```cpp
#include <iostream>
#include <string>
using namespace std;
int count_letters(string sentence) {
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
if (isalpha(sentence[i])) {
count++;
}
}
return count;
}
int main() {
string sentence;
cout << "请输入一条英文句子:";
getline(cin, sentence);
int letter_count = count_letters(sentence);
cout << "这条英文句子中字母的个数为:" << letter_count << endl;
return 0;
}
```
这个程序中,`count_letters` 函数使用 `isalpha` 函数判断字符串中的每个字符是否为字母,然后将符合条件的字符计数并返回。在主程序中,首先要求用户输入一条英文句子,然后调用 `count_letters` 函数计算字母个数并输出结果。