Java输出字符串大小写字母个数【Java学习笔记】

时间:2023-02-26 15:05:40
/*
时间:2014年12月21日20:11:45
功能:编程输出一个字符串中大写字母、小写字母以及非英文字母个数
以为想到转大小写就机智了,结果想起来长度都一样,又SB了……
*/

public class Test {
public static void main(String[] args) {
String s = "ABCabc$%hello&*";
//String sL = s.toLowerCase();//转小写
//String sU = s.toUpperCase();//转大写

int Lower = 0;
int Upper = 0;
int Other = 0;
//方法一:
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(c >= 'a' && c<= 'z') {
Lower ++;
} else if(c >= 'A' && c <= 'Z') {
Upper ++;
} else {
Other ++;
}
}
System.out.println("大写字母有 "+ Lower + " 个");
System.out.println("小写字母有 "+ Upper + " 个");
System.out.println("非英文字母有 "+ Other + " 个");

/*方法二:
String sL ="qwertyuiopasdfghjklzxcvbnm";
String sU = "QWERTYUIOPASDFGHJKLZXCVBNM";
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(sL.indexOf(c) != -1) {//在sL出现过
Lower ++;
} else if(sU.indexOf(c) != -1) {//在sU出现过
Upper ++;
} else {
Other ++;
}
}
System.out.println("大写字母有 "+ Lower + " 个");
System.out.println("小写字母有 "+ Upper + " 个");
System.out.println("非英文字母有 "+ Other + " 个");
*/

/*方法三(注意从包装类Character中找相关方法):
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(Character.isLowerCase(c)) {
Lower ++;
} else if(Character.isUpperCase(c)) {
Upper ++;
} else {
Other ++;
}
}
System.out.println("大写字母有 "+ Lower + " 个");
System.out.println("小写字母有 "+ Upper + " 个");
System.out.println("非英文字母有 "+ Other + " 个");
*/
}
}


/*********输出结果:

大写字母有 8 个
小写字母有 3 个
非英文字母有 4 个

************/

to be continued ...