将字符串按一定规则进行分词,并将每个词出现的次数记录在map中
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringTokenizer st = new StringTokenizer(s,"./:");
final Map<String,Integer> map = new HashMap<String,Integer>();
while(st.hasMoreElements()){
String temp = st.nextToken();
if(map.get(temp)==null){
map.put(temp,1);
}
else {
map.put(temp,map.get(temp)+1);
}
}
System.out.println(map);
sc.close();
}
} 结果
注意
如果我们在StringTokenizer(String s , spilit , ture) 加上了true,那么也会将分词的符号分出来。
StringTokenizer st = new StringTokenizer(s,"./:",true);
得到的结果就能在map中显示符号出现的次数了。

京公网安备 11010502036488号