Talk is cheap, show me the code.
一、問題描述
輸入一行字符,分別統計出包含英文字母、空格、數字和其它字符的個數。
/**
* 統計出英文字母字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getEnglishCharCount(String str)
{
return 0;
}
/**
* 統計出空格字符的個數。
*
* @param str 需要輸入的字符串
* @return 空格的個數
*/
public static int getBlankCharCount(String str)
{
return 0;
}
/**
* 統計出數字字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getNumberCharCount(String str)
{
return 0;
}
/**
* 統計出其它字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getOtherCharCount(String str)
{
return 0;
}
輸入描述:
輸入一行字符串,可以有空格
輸出描述:
統計其中英文字符,空格字符,數字字符,其他字符的個數
輸入例子:
1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\/;p0-=\][
輸出例子:
26
3
10
12
二、問題分析
純屬字符串處理。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string s;
while (getline(cin, s))
{
int alpha = 0, digit = 0, blank = 0, other = 0;
for (int i = 0; i < s.size(); i++)
{
if (isalpha(s[i]))
{
alpha++;
} else if (isdigit(s[i])){
digit++;
} else if (s[i] == ' '){
blank++;
} else {
other++;
}
}
cout << alpha << endl;
cout << blank << endl;
cout << digit << endl;
cout << other << endl;
}
return 0;
}