1.使用map集合
public class test01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);//获取scanner对象
System.out.println("请输入一个字符串:");
String sc = scanner.next();//接收字符串
char[] chs = sc.toCharArray();//字符串转数组
//调用wordCount方法获取字符串
System.out.println(wordCount(chs));
}
//定义处理字符串的方法
public static Map<Character,Integer> wordCount(char[] chs){
//创建集合对象
TreeMap<Character,Integer> map = new TreeMap<>();
for (int i = 0; i <chs.length ; i++) {//遍历数组的每个元素
if(map.containsKey(chs[i])){//判断当前元素是否存在
//如果存在,则在集合元素个数加1
map.put(chs[i],map.get(chs[i])+1);
}
else {//否则直接把元素加到集合,元素个数为1,
map.put(chs[i],1);
}
//简单的三目运算 和if -else一样
//判断当前是否有这个值,有的化,直接在值上加1,没有的化,把元素的键加到集合map。值也加1
//map.put(chs[i],map.containsKey(chs[i])?map.get(chs[i])+1:1);
}return map;//返回集合
}
}