求出字符串中有多少种字符,以及每个字符的个数
static void printCharInfo(String str)
例如有字符串 str=”apple is a apple.”;
结果应该是
a:3
p:4
l:2
e:2
:3
i:1
s:1
.:1
解题思路:
1.将字符串转换为char数组
2.将char数组 转换为 int 类型数组
3.对int数组排序
4.统计int数组中相同数字的个数,并输出
package _7._28;
import java.util.Arrays;
/**
* Created by mac on 2017/7/28.
*/
public class Test_6 {
static void printCharInfo(String str){
char[] ch = str.toCharArray();
int[] x = new int[str.length()];
for (int i = 0;i<str.length();i++){
x[i] = ch[i];
}
Arrays.sort(x);//排序
int startIndex = 0;
int i = 0;
while (i < x.length){
if(x[i] != x[startIndex]){
System.out.println((char)x[startIndex]+":"+(i-startIndex));
startIndex = i;
}
//每次一定要检查是否到数组结尾
if (i == x.length-1){
System.out.println((char)x[startIndex]+":"+(i+1-startIndex));
}
i++;
}
}
public static void main(String[] args) {
String string = "你好世界,Hello world";
printCharInfo(string);
}
}