需要一点点澄清

时间:2018-11-11 14:20:01

标签: java

你们能告诉我count[word.charAt(i)]++在此代码和overall--中到底是做什么的吗?

public static void main(String[] args) {
    String S = "Some random text to test.";
    int count[] = new int[124];
    for (int i=0; i< S.length(); i++) {
       count[S.charAt(i)]++;
       System.out.print(count[S.charAt(i)] + " ");
    }
    int max = 1;
    char result = ' ';

    for (int i = 0; i < S.length(); i++) {
        if (max < count[S.charAt(i)] && S.charAt(i) != ' ') {
            max = count[S.charAt(i)];
            result = S.charAt(i);
        }
    }
    System.out.println(result);
}

count[S.charAt(i)]的印刷只是我试图解决的问题。

2 个答案:

答案 0 :(得分:0)

S.charAt(i)返回该字符串 S i-th位置的字符。

然后count[S.charAt(i)]将像这样执行。假设您得到“ S”作为字符。那么'S'的字符值将为83。因此,它将采用 count数组中的83索引元素并将其递增1。

答案 1 :(得分:0)

word.charAt(i)返回字符串word 中第 i个索引处的字符。

count是一个int数组,具有自动全零int count[] = new int[124];

count[i]++将索引{strong> i 中count中的值增加1。

在这里,您正在传递word.charAt(i)作为索引,即count[word.charAt(i)]++,它的作用是:

-首先评估word.charAt(i),但 请注意,索引我必须是整数!
因此会自动获取字符的 ASCII 值。例如('a'= 97,'b'= 98 ..)

-然后count[ASCII number returned]++(例如count[97]++)将递增,现在count[97] = 1

但是请注意,如果您的 String 具有'}',则会出现索引超出范围例外,因为其 ASCII 值为125 ;和125 > 124 计数大小

相关问题