import java.util.*; public class test{ public static void main(String[] arg) { String str="How do you do what are you are what"; String[] st=str.split(" "); String word=null; int m=0; ArrayList<String> al=new ArrayList<String>(); for(String s:st) { al.add(s); } Collections.sort(al); LinkedHashSet<String> hs=new LinkedHashSet<String>(); HashMap<String,Integer> hm=new HashMap<String,Integer>(); for(int i=0;i<al.size();i++) hs.add(al.get(i)); Iterator it=hs.iterator(); word=(String)it.next();
2. 用MAP做統計 的到一個 單字 次數 的 MAP
3. 輸出
2. 統計 用MAP
3. 輸出
1. 分割字串 用split得到一個數組
2. 用Map統計, 得到一個 單字 次數的Map
3. 輸出。
public class test{
public static void main(String[] arg)
{
String str="How do you do what are you are what";
String[] st=str.split(" ");
String word=null;
int m=0;
ArrayList<String> al=new ArrayList<String>();
for(String s:st)
{
al.add(s);
}
Collections.sort(al);
LinkedHashSet<String> hs=new LinkedHashSet<String>();
HashMap<String,Integer> hm=new HashMap<String,Integer>();
for(int i=0;i<al.size();i++)
hs.add(al.get(i));
Iterator it=hs.iterator();
word=(String)it.next();
for(int i=1;i<al.size();i++)
{
m++;
if(!(word.equals(al.get(i))))
{
hm.put(word,m);
word=(String)it.next();
m=0;
}
}
hm.put(word,m+1);
Set ks=hm.keySet();
Iterator it1=ks.iterator();
while(it1.hasNext())
{
String key=(String)it1.next();
Integer value=(Integer)hm.get(key);
System.out.println(key+":"+value);
}
}
}
输出:
are:2
what:2
you:2
do:2
How:1