(java实现)
题目描述:
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
本题包含多组输入。
输入描述:
输入一行字符串,可以有空格
输出描述:
统计其中英文字符,空格字符,数字字符,其他字符的个数
示例1:
输入
1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][
输出
26
3
10
12
问题分析:
需要统计字符种类数目,有两种思路
思路一:通过比对ASCII码来实现;
思路二:通过调用内置判断函数来实现;
相关知识:
思路二:相关函数
1、isLetter()
是否是一个字母
2、isDigit()
是否是一个数字字符
3、isWhitespace()
是否是一个空白字符
4、isUpperCase()
是否是大写字母
5、isLowerCase()
是否是小写字母
6、toUpperCase()
指定字母的大写形式
7、toLowerCase()
指定字母的小写形式
8、toString()
返回字符的字符串形式,字符串的长度仅为1
例子
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
}
}
参考代码:
思路一实现:
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while (input.hasNext())
{
String str = input.nextLine();
char[] ch = str.toCharArray();
int[] res = new int[4];
for (int i=0; i<ch.length; i++)
{
if((ch[i]>='A'&&ch[i]<='Z') || (ch[i]>='a'&&ch[i]<='z'))
res[0]++;
else if (' ' == ch[i])
res[1]++;
else if (ch[i]>='0' && ch[i]<='9')
res[2]++;
else
res[3]++;
}
for (int i=0; i<4; i++)
System.out.println(res[i]);
}
}
}
思路二实现:
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
while (input.hasNext())
{
String str = input.nextLine();
char[] ch = str.toCharArray();
int f1=0, f2=0, f3=0, f4=0;
for (int i=0; i<ch.length; i++)
{
if (Character.isLetter(ch[i]))
{
f1++;
}else if (Character.isSpace(ch[i]))
{
f2++;
}else if (Character.isDigit(ch[i]))
{
f3++;
}else
{
f4++;
}
}
System.out.println(f1);
System.out.println(f2);
System.out.println(f3);
System.out.println(f4);
}
}
}