统计一个字符串中数字字符和字母的个数分别是多少。 c++编程

2025-05-12 14:33:09
推荐回答(4个)
回答(1):

#include
#include
using namespace std ;

bool IsNumber(const char c);
bool IsLetter(const char c);

int main(int argc, char *argv[])
{
cout << "输入字符串:" << endl;
string str;
cin >> str;

const char * c_str = str.c_str();
int numberCount = 0, letterCount = 0;
for(size_t i = 0; i != str.length(); ++i)
{
if(IsNumber(c_str[i]))
{
++numberCount;
}
else if(IsLetter(c_str[i]))
{
++letterCount;
}
}

cout << "数字有:"
<< numberCount
<< "个"
<< endl
<< "字母有:"
<< letterCount
<< "个"
<< endl;
return 0;
}

bool IsNumber(const char c)
{
if(c >= 48 && c <= 57)
{
return true;
}
else
{
return false;
}
}

bool IsLetter(const char c)
{
if((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
{
return true;
}
else
{
return false;
}
}

回答(2):

C的 我改了下 你自己看看 要是还不行 就自己改改
#include
using namespace std;
void count(char *s, int *digit, int *letter, int *other)
{
int i;
for(i=0;s[i]!='\0';i++)
{
if(s[i]>='a'&&s[i]<='z' || s[i]>='A'&&s[i]<='Z')
(*letter)++;
else if(s[i]>'0'&&s[i]<'9')
(*digit)++;
else
(*other)++;
}
}
void main()
{
int x=0,y=0,z=0;
char ch[80];
cout<<"Enter a string:"< gets(ch);
count(ch,&x,&y,&z);
cout<<"数字有:<}

回答(3):

//希望对楼主有个小小的帮助。。。
//0~9是48~57,A~Z是65~90,a~z是97~122
#include
#include
#include
using namespace std;
bool IsNum(char elem)
{
if(elem>=48&&elem<=57)
return true;
else
return false;
}
bool IsChar(char elem)
{
if((elem>=65&&elem<=90)||(elem>=97&&elem<=122))
return true;
else
return false;

}
int main()
{
int countNum,coutChar;
string strLine;
getline(cin,strLine);
countNum=count_if(strLine.begin(),strLine.end(),IsNum);
coutChar=count_if(strLine.begin(),strLine.end(),IsChar);
cout<<"countNum:"< cout<<"coutChar:"< return 0;
}

回答(4):

数字和字母的ascii码中的范围是不同的,自己查查吧,书后面可能有啊。