API文档charAt(int index)是这样定义的:
charAt(char index):Returns the char
value at the specified index.在指定的索引返回字符的值;
示例
API文档isLowerCase是这样定义的:
isLowerCase(char ch):Determines if the specified character is a lowercase character.确定如果指定的字符是一个小写字母开头;
API文档isUpperCase是这样定义的:
isUpperCase(char ch): Determines if the specified character is an uppercase character.确定如果指定的字符是一个大写字母开头。
通过一个简单的小例子来运用;
编写一个程序,要求输出一个字符串中大小写字母数以及其他字符数:
一般的算法是:
public class TestFinally {
public static void main(String[] args) {
int count1=0;int count2 = 0;int count3 = 0;
String s = "jndhuf455NJKHJ455D";
for (int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z') {
count1++;
} else if (c >= 'A' && c <= 'Z') {
count2++;
} else {
count3++;
}
}
System.out.println(count1 + " - " + count2 + " - " + count3);
}
}
输出结果:7 - 6 - 6
使用isLowerCase以及isUppercase:
public class TestFinally {
public static void main(String[] args) {
int count1=1;int count2 = 0;int count3 = 0;
String s = "jndhuf455NJKHJ455D";
for(int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if (Character.isLowerCase(c)) {
count1++;
}
else if (Character.isUpperCase(c)) {
count2++;
}
else {
count3++;
}
}
System.out.println(count1 + " - " + count2 + " - " + count3);
}
}
运行输出结果:7 - 6 - 6