给固定字符串切割开并记录每隔英文字母出现的次数
1.split()函数
用split()函数来分割字符串时注意分割的符号,如果只有单纯的字母就用split(""),例如
String s="fasf";
String[ ] st = s.split("");
2.大家需要字母比较是使用equals方法
st[i].equals("a"
接下来就是这道题目的所有代码了
public static <Char> void main(String[] args) {
String s="fasf";
String[ ] st = s.split("");
int countA = 0;
int countF = 0;
int countS = 0;
for (int i = 0; i < st.length; i++) {
System.out.println(st[i]);
if(st[i].equals("a")){
countA+=1;
}else if (st[i].equals("f")){
countF++;
}else if (st[i].equals("s")){
countS++;
}
}
System.out.println("a字母出现的次数是:"+countA);
System.out.println("f字母出现的次数是:"+countF);
System.out.println("s字母出现的次数是:"+countS);
}
当然这只是比较基础的写法,只可以解决比较短的字符串,若字符串比较长时,可以使用hashMap解决,等到我学会时更新,期待对大家有所帮助!