2013-03-20 34 views
0

我必須讀取字符串"hello world"並僅使用for循環輸出每個字母的頻率。教員暗示,我需要用兩個迴路,給了我們下面的代碼開始:使用兩個for-loops計算字符串中的字母

int ch, count; 
for (ch ='a'; ch <='z'; ch++) { 
    //count the number of occurrences in a line 
    //Print the count>0 
} 

編輯:我想我會死靈這個問題,並張貼我發現在一年前,由於該解決方案事實上這個問題已經得到了不錯的點擊量。

int count; 
int value; 
for (int i=65; i<91; i++) { 
    count=0; 
    for (int j=0; j<S.length; j++) { 
     value=(int)S[j]; 
     if (value == i) { 
      count++; 
     } 
    } 
    if (count>0) 
     System.out.println((char)i+" -- "+count); 
} 
+0

對於每個字符,遍歷字符串,並增加計數器,如果你看到它。 – sdasdadas 2013-03-20 19:27:04

+6

所以你已經嘗試過什麼都沒有? – 2013-03-20 19:28:45

+0

你可以請張貼你的老師給你的代碼。 – debianplebian 2013-03-20 19:29:03

回答

0
int count; 
int value; 
    for (int i=65; i<91; i++) { 
     count=0; 
     for (int j=0; j<S.length; j++) { 
     value=(int)S[j]; 
     if (value == i) { 
     count++; 
     } 
    } 
    if (count>0) 
     System.out.println((char)i+" -- "+count); 
} 
5

在第二個循環中,只需遍歷字符串的每個字符並將其與第一個for循環的當前字符進行比較。

(而不是解決方案,我會做,只是跟着你的導師暗示)

另一種方法是用字符作爲鍵和事件作爲值的計數器的地圖內存儲的值。

HashMap<Character,Integer> map = new HashMap<>(); 

for (int ii=0; ii<string.length; ii++) { 
    char c = string.charAt(ii); 
    if (map.containsKey(c)) { 
     map.put(c, get(c)++); 
    } else { 
     map.put(c, 1); 
    } 
} 

UPDATE:

//iterating on the map to output values: 
for (char key : map.keySet()) { 
    System.out.println(key+": "+map.get(key)); 
} 
+0

是的,好提示。不要忘記在每個字符後重置計數。 – 2013-03-20 19:31:43

+0

這將有點過度的做法。例如字母「l」將顯示兩次。你需要一個moe循環之前,消除重複,使用字符串與消除重複在外部,在內部使用全字符串。 – 2013-03-20 19:40:50

+0

還沒有了解hashmaps – Tdorno 2013-03-21 13:26:57

1

我會用一個簡單的數組。只需將每個字母轉換爲索引並在該索引處增加數組。

int letters[26]; 
int index = ch - 'a'; 
letters[index]++; 
+0

是的,但我怎樣交織一個計數器,當讀取給定的索引值時增加1(從0開始)?這是我困惑的部分。 – Tdorno 2013-03-20 19:52:06

+0

其他角色怎麼樣,比如'!','+','>'? – 2013-03-20 19:53:06

+0

@Tdorno'字母[索引] ++;'是計數器。 – andre 2013-03-20 20:21:35

1

要建立過sdasdadas的評論,並讓各自的答案:

for循環外將通過字母表中的每個字符旋轉,保持計數(這就需要將重置每次外環執行。)內循環循環遍歷「hello world」字符串,如果找到用作outer for循環的當前參數的字符,則遞增計數器。

UPDATE 我不能評論安德烈的答案,但我可以提供一些僞代碼來解決你的評論中關於櫃檯的含義。

int i; 
for (ch characterOuter : alphabet){ //for each character in the alphabet 
    i = 0 //i starts at zero, and returns to zero for each iteration <-----THIS 
    for (ch characterInner : "hello world"){ 
     if (characterOuter == characterInner){ 
      i++; //increase i by 1 <-----AND THIS 
     }//end if 
    }//end innerfor 
    if (i > 0) { 
     print(characterOuter + " -- " + i); 
    } //end if; <---------------- this if statement was missing 
}//end outer for 

另外,參見this question

+0

我喜歡Ben的方法,但它重複顯示每個字符一次 – Tdorno 2013-03-21 17:58:09

+0

你的意思是你的執行被陷入無限循環,還是你的意思是它打印每個字符的每個實例? – eenblam 2013-03-22 03:16:47

+0

哦,我明白了。你只需要另一個if語句。我會調整代碼。 – eenblam 2013-03-22 03:20:54

相關問題