前几天写JavaScript时就遇到这个代码,用JavaScript写下来感觉很轻松,用java试试,浅尝,浅尝以下:
public class str {
public static void main(String[] args) {
String str ="abcdabcdgydgdbasjsh";
// 统计str中的字母出现的次数
// 1.首先将str数据放在char数组容器中
char[] cho=str.toCharArray();
System.out.println(Arrays.toString(cho));
for (int i = 0; i < str.length(); i++) {
// 计数器count=0
int count=0;
// 如果cho数组i为的数据为0,直接pass,对应cho【j】=0
if (cho[i] !=0) {
// c是i位数据
char c =cho[i];
// 遍历cho数组,如果cho[j]数据等于cho[i]位数据,说明有重复值,计数器加一,传入cho数组的j(i)位为0,下一次循环时,会自动略过j位
for (int j = 0; j < cho.length; j++) {
if(c==cho[j]){
count++;
cho[j]=0;
}
}
System.out.println(c+"共有"+count+"个");
}
}
}
}