字符串中取单词的个数
一个字符串内容:String str = "apple orange banana apple hello orange apple" ;
输出的内容是:
apple 3
orange 2
banana 1
hello 1
求解决!
import java.util.*; public class SplitStringCounter { public static void main(String[] args) { String str = "apple orange banana apple hello orange apple"; String[] splitStringArray = str.split(" "); Map<String, Integer> splitStringMap = new HashMap<>(); for (String splitStringElement : splitStringArray) { if (splitStringMap.containsKey(splitStringElement)) { splitStringMap.put( splitStringElement, splitStringMap.get(splitStringElement) + 1); } else { splitStringMap.put( splitStringElement, 1); } } for (String splitStringMapKey : splitStringMap.keySet()) { System.out.println( splitStringMapKey + ":" + splitStringMap.get(splitStringMapKey)); } } }