描述 |
輸入一行字符,分別統計出包含英文字母、空格、數字和其它字符的個數。
/**
|
知識點 |
字符串 |
運行時間限制 |
10M |
內存限制 |
128 |
輸入 |
輸入一行字符串,可以有空格 |
輸出 |
統計其中英文字符,空格字符,數字字符,其他字符的個數 |
樣例輸入 |
1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][ |
樣例輸出 |
26 3 10 12 |
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner sca = new Scanner(System.in);
String str = sca.nextLine();
sca.close();
System.out.println(getEnglishCharCount(str));
System.out.println(getBlankCharCount(str));
System.out.println(getNumberCharCount(str));
System.out.println(getOtherCharCount(str));
}
/**
* 統計出英文字母字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getEnglishCharCount(String str)
{
int[] count = new int[128];
int letterCount = 0;
for(int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
for(int i = 'a';i <= 'z';i++)
{
letterCount += count[i];
}
for(int i = 'A';i <= 'Z';i++)
{
letterCount += count[i];
}
return letterCount;
}
/**
* 統計出空格字符的個數。
*
* @param str 需要輸入的字符串
* @return 空格的個數
*/
public static int getBlankCharCount(String str)
{
int[] count = new int[128];
int spaceCount = 0;
for(int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
spaceCount = count[' '];
return spaceCount;
}
/**
* 統計出數字字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getNumberCharCount(String str)
{
int[] count = new int[128];
int numberCount = 0;
for(int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
for(int i = '0';i <= '9';i++)
{
numberCount += count[i];
}
return numberCount;
}
/**
* 統計出其它字符的個數。
*
* @param str 需要輸入的字符串
* @return 英文字母的個數
*/
public static int getOtherCharCount(String str)
{
int[] count = new int[128];
int otherCount = 0;
for(int i = 0; i < str.length(); i++)
{
count[str.charAt(i)]++;
}
for(int i = 0; i < 128; i++)
{
if((i == ' ') || ((i >= '0') && (i <= '9')) || (((i >= 'a') && (i <= 'z'))||((i >= 'A') && (i <= 'Z'))))
{
continue;
}
otherCount += count[i];
}
return otherCount;
}
}