統計字符串中出現某子串的次數的一個算法【csdn總結】

 有一個String,如“張三,李四,張三,小王,張三”;
輸出: 張三:3,李四:1,小王:1
輸出的具體格式不限,輸出關鍵字和出現次數即可,另外速度越快越好。

可用以下方法解決:

import java.util.HashMap;
import java.util.Map;

public class CountTest {

    public static void main(String[] args) {
        String s = "張三,李四,張三,小王,張三";
        Map<String, Integer> map = new HashMap<String, Integer>();
        String[] ss = s.split(",");
        for (String temp : ss) {
            if (map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            } else {
                map.put(temp, 1);
            }
        }
        System.out.println(map);
    }
}

 

總結自csdn.net

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章