统计一个字符串中包含字母的个数。
public static int countLetters(String s)
编写测试程序调用countLetters("Beijing 2020"
方法并显示它的返回值7。
public class Test3 {
public static void main(String[] args) {
System.out.println(countLetters("Beijing 2020"));
}
public static int countLetters(String s){
int res = 0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if((c >= 'a' && c<='z') || (c >= 'A' && c<='Z')) {
res++;
}
}
return res;
}
}
这样?
public static int countLetters(String s) {
char[] charArry = s.toCharArray();
int count = 0;
for (char c : charArry) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
count++;
}
}
return count;
}
结果:
public static int countLetters(String s){
return s.replaceAll("[^a-zA-Z]", "").length();
}
public class Test {
public static void main(String[] args) {
System.out.println(countLetters("Beijing 2020"));
}
public static int countLetters(String s){
int count = 0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
count += 1;
}
}
return count;
}
}
public static void main(String[] args) {
//将此扫描仪推进到当前行并返回跳过的输入。
String s = "Beijing 2020";
//定义统计字母的变量
int charCount = 0;
//定义统计数字的变量
int numCount = 0;
//遍历字符串
//返回此字符串的长度。
for (int i = 0; i < s.length(); i++) {
//取出字符串中的字符,判断是否为字母
//返回指定索引处的char值。 指数范围从0到length() - 1 。 序列的第一个char值是索引0 ,下一个索引为1 ,依此类推,就像数组索引一样。
if ((s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') || (s.charAt(i) >= 'a' && s.charAt(i) <= 'z')) {
charCount++;
} else if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {//判断字符串中的字符是否为数字
numCount++;
}
}
System.out.println("字母:" + charCount + " 数字:" + numCount);
}