还有哪些方法可以判断字符串里有多少个数字,多少个字母,其他符号等等
######
#include
#include
#include
using namespace std;
int main()
{char n;
int a,b,c,other;
cout<<"请输入字符串"<while((n=getchar())!='\n')
{
if((n>='A' && n<='Z')||(n>='a' && n<='z'))
a++;
else if(n>='0'&&n<='9')
b++;
else if(n==' ')
c++;
else
other++;}
cout<<"英文字母个数="<"数 字 个 数 ="<"空 格 字 数 ="<"其他字符个数="<return 0;
}
``` #include
#include
#include
using namespace std;
int main()
{char n;
int a,b,c,other;
cout<<"请输入字符串"<while((n=getchar())!='\n')
{
if((n>='A' && n<='Z')||(n>='a' && n<='z'))
a++;
else if(n>='0'&&n<='9')
b++;
else if(n==' ')
c++;
else
other++;}
cout<<"英文字母个数="<"数 字 个 数 ="<"空 格 字 数 ="<"其他字符个数="<return 0;
}
######n

上图为其中一个测试结果,显然其他字符个数和数字字符个数都不符合实际情况
#include <iostream>
#include <cctype>
int main() {
// 定义字符串变量
std::string str = "Hello, World!";
// 定义计数器变量
int num_digits = 0;
int num_letters = 0;
int num_other = 0;
// 遍历字符串中的每个字符
for (char c : str) {
// 使用 C++ 库函数 isdigit() 判断是否为数字
if (isdigit(c)) {
num_digits++;
}
// 使用 C++ 库函数 isalpha() 判断是否为字母
else if (isalpha(c)) {
num_letters++;
}
// 剩余的字符都是其他符号
else {
num_other++;
}
}
// 输出结果
std::cout << "字符串中共有 " << num_digits << " 个数字、"
<< num_letters << " 个字母和 " << num_other << " 个其他符号。" << std::endl;
return 0;
}
没有初始化变量
int a = 0,b = 0,c = 0,other = 0;