我希望按升序查找每個字符的發生次數。按順序計算字符的發生次數
例如,輸入輸出abcddec
應a1b1c1d1d2e1c2
,但我 代碼是給我輸出a1b1c2d2e1c2
我應該做什麼樣的變化?
package com.Java8;
public class Occurences {
public static void main(String[] args) {
String str = "abb";
char[] arr = str.toCharArray();
String result = "";
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
result = result + arr[i] + count;
}
System.out.println(result);
}
}
你不需要遍歷字符串,你實際上只需要一個'for'循環。你只需要存儲你遇到的字符的出現。 –
看看這裏以及 - http://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string – sash