我写了一个接受字符串的类,计算字符串中每个字母的出现,然后打印每个字母的出现。我希望按字母顺序显示,但不确定如何执行此操作。
import java.util.ArrayList; // import the ArrayList class
class CryptCmd {
public static void CryptCmd(String str) {
ArrayList<String> occurs = new ArrayList<>();
final int MAX_CHAR = 256;
// Create an array of size 256 i.e. ASCII_SIZE
int[] count = new int[MAX_CHAR];
int len = str.length();
// Initialize count array index
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char[] ch = new char[str.length()];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
occurs.add("Number of Occurrence of " + str.charAt(i) + " is: " + count[str.charAt(i)] + "\n");
}
System.out.println(String.join("",occurs));
int total = 0;
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != ' ')
total++;
}
System.out.println("Total chars is " + total);
}
}
到目前为止,打印内容以找到信件的顺序显示,即>
"Hello" =
Number of Occurrence of H is: 1
Number of Occurrence of e is: 1
Number of Occurrence of l is: 2
Number of Occurrence of o is: 1
Total chars is 5
所需的输出是这个,按字母顺序排列,即
"Hello" =
Number of Occurrence of e is: 1
Number of Occurrence of H is: 1
Number of Occurrence of l is: 2
Number of Occurrence of o is: 1
Total chars is 5
我写了一个接受字符串的类,计算字符串中每个字母的出现,然后打印每个字母的出现。我希望按字母顺序显示,但不确定...
它返回是因为H
在您的情况下为大写字母,而在ASCII ordering中为小写字母。