通过正则表达式
public class String_20211119_02 {
public static void main(String[] args) {
String str = "Beijing 2008";
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group() + "长度为:" + matcher.group().length());
}
}
}
String字符串转换字符数组,统计数组长度
public static int countLetters(String s){
int res = 0;
for(int i = 0;i < s.length();i++){
if(s.charAt(i) >= 'a' && s.charAt(i) <= 'z' || s.charAt(i) >= 'A' && s.charAt(i) <= 'Z'){
res ++;
}
}
return res;
}
string有个转成char数组的方法
转成char[]后遍历
通过ascii码判断是不是字母
用一个int变量去统计数量
循环结束后返回结果
提供思路,代码就不给了,自己写比较有用
解题思路:这个统计字符串中字母个数,主要是通过ASCII去判断的,所以遍历传入的字符串,然后使用字符串的charAt方法得到一个字符串中每个字符在与ASCII比较,比较时注意大写字母和小写字母
方法一:直接把非字符替换掉,求剩余的字符长度
public static int countLetters(String s) {
return s.replaceAll("[^a-zA-Z]","").length();
}
方法二:
public static int countLetters(String s) {
return (int)s.chars().filter( v -> v>= 'a' && v<='z' || v>= 'A' && v <= 'Z').count();
}