package study;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
/*输入字符串统计里面单词的个数,以及里面字母出现的次数*/
public class StringDemo {
public static void main(String[] args) {
System.out.println("请输入一个字符串:");
Scanner reader = new Scanner(System.in);
String in = reader.nextLine();
// StringBuilder sb = wordCount(in);
System.out.println(wordCount(in));
System.out.println(chartCount(in));
}
public static TreeSet wordCount(String str) {//单词个数统计
// StringBuilder sb = new StringBuilder();
// sb.append("[");
// String[] word = str.split(" ");
// for(int i = 0;i < word.length - 1;i++) {
// sb.append(word[i] + ",");
// }
// sb.append(word[word.length - 1]);
// sb.append("] 共" + word.length + "个单词");
// System.out.println(count);
// return sb;
/*上面的收集方式不能排除相同单词的出现,考虑使用set集合来过滤*/
String[] token = str.split(" ");
return new TreeSet(Arrays.asList(token));
}
/*
* 考虑用键值对来存储每个字符的个数
* */
public static TreeMap chartCount(String str) {//字符个数统计
char[] charArray = str.toCharArray();
TreeMap<Character,Integer> tp = new TreeMap<Character,Integer>();
for(int i = 0;i < charArray.length;i++) {
if(!tp.containsKey(charArray[i])) {
tp.put(charArray[i], 1);
}else {
int count = tp.get(charArray[i]) + 1;
tp.put(charArray[i], count);//根据TreeMap源码意思,当出现相同键,但其值不同,会用新添加的值进行替代
}
}
return tp;
}
}
java中TreeMap统计字符个数
最新推荐文章于 2021-07-04 20:08:33 发布