Java 统计一个字符串中每个单词,或者字母出现的次数

来源:互联网 发布:淘宝有个雪山狗粮真假 编辑:程序博客网 时间:2024/05/16 05:54
package cn.itcast.demo24;


import java.util.HashMap;


/*
 * 用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you 
must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)
 */
public class Demo22 {
public static void main(String[] args) {
String s = "If you want to change your fate I think you " +
"must come to the dark horse to learn java";
get(s);
}
public static void get(String s){
String[] str = s.split(" ");
HashMap<String, Integer> map = new HashMap<>();
for(String ss:str){
Integer num = map.get(ss);
if(num==null){
map.put(ss, 1);                  
}else {
map.put(ss, ++num);   ...................... //此处如果写为  map.put(ss,num++),就会错误,
//否则就写为  num++;
//          map.put(ss,num);
}
}
System.out.println(map);

}

  下面这样写也可以

/*for(String ss:str){
Integer num = map.get(ss);
if(num==null){
num = 1;                 
}else {
num++;
}
map.put(ss,num);
*/
}
0 0
原创粉丝点击