import java.util.*;
/*
* @author 詩語江南
* @function 統(tǒng)計(jì)字符串中的重復(fù)部分并整理輸出,
* 我用了兩種方法來做.
*/
public class StrShowTimes{
public static void main(String[] r){
String str = "帥哥,美女,帥哥,野獸,美女,帥哥";
Map s1 = strTimesWithMap(str);
Set keys = s1.keySet();
Iterator it = keys.iterator();
while(it.hasNext()){
String key = (String)it.next();
int value = (Integer) s1.get(key);
System.out.print(key + ": " + value+ ", ");
}
System.out.println();
strTimesWithArray(str);
}
//使用HashMap的方法,該方法比較簡(jiǎn)單
public static Map strTimesWithMap(String str){
//key: 子字符串 String , value: 重復(fù)次數(shù) Integer
Map strMap = new HashMap();
String[] strArr = str.split(",");
for(int i =0; i< strArr.length ; i++){
String key = strArr[i] ;
if(strMap.containsKey(key)){
int value = (Integer) strMap.get(key);
strMap.put(key,++value);
}else{
strMap.put(key,1);
}
}
return strMap;
}
//使用雙數(shù)組的方法,一個(gè)字符串?dāng)?shù)組存字符串
//一個(gè)整形數(shù)組存與字符串?dāng)?shù)組對(duì)應(yīng)位置上的字符串出現(xiàn)的次數(shù)
public static void strTimesWithArray(String str){
String[] tempArr = str.split(",");
int i , end = 0 , len = tempArr.length;
String[] strArr = new String[len];
int[] intArr = new int[len];
boolean isChange ;
for(i = 0 ; i < len ; i++){
isChange = false;
for(int j = 0 ; j < end ; j++){
if(tempArr[i].equals(strArr[j])){
intArr[j] = intArr[j] +1 ;
isChange = true;
break;
}
}
if(isChange) continue;
strArr[end] = tempArr[i];
intArr[end++] = 1;
}
for(i = 0 ; i < end ; i++){
System.out.print(strArr[i] + ": " + intArr[i] + " ");
}
}
}
posted on 2007-10-05 13:36
詩語江南 閱讀(1677)
評(píng)論(3) 編輯 收藏 所屬分類:
Core JAVA