1. 程式人生 > >演算法之“統計字串中單詞的個數”

演算法之“統計字串中單詞的個數”

如,給定String,求此字串的單詞數量。字串不包括標點,大寫字母。例如String str="hello world hello hi";,單詞數量為3,分別是:hello world hello hi 。

public static void main(String[] args){
    int count=0;
    String str="hello world hello hi";
    String newStr="";
    HashMap<String,String> map=new HashMap<String,String>;
    String[] arr=str.split(" ");
    for(int i=0;i<arr.length;i++){
        if(!map.containskey(arr[i])){
            map.put(arr[i],"1");
            count++;
            newStr+=arr[i];
          }
      }
    System.out.println("單詞的個數為:"+count+":"+newStr);

    }