【问题标题】:count occurrence of a character in a given string using one for loop with java使用 java 的一个 for 循环计算给定字符串中字符的出现次数
【发布时间】:2018-11-05 18:12:57
【问题描述】:

这是参考代码:

    // 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)
            System.out.println("Number of Occurrence of " +
                    str.charAt(i) + " is:" + count[str.charAt(i)]);
    }

输出应该类似于:

“x”出现的次数是:“它出现的次数”

如果该字母以前出现过,则只显示该出现一次。


我使用 2 个 for 循环得到了逻辑,虽然我的老师说它可以只使用 1 个 for 循环来执行这个应用程序。

我遇到的问题是:
只有当角色彼此相邻时,我才能找到是否已经找到角色。

如果没有另一个 for 循环,您如何检查是否找到了所有先前的字符?

【问题讨论】:

标签: java for-loop


【解决方案1】:

使用Map&lt;Integer, Integer&gt;(键:字符,值:字符数)来存储您的字符数。

你只需要循环你的角色一次:

String input = "this is input string";
Map<Integer, Integer> charCount = new LinkedHashMap<>();
for (int c : input.toCharArray()) {
    if (!charCount.containsKey(c)) {
       charCount.put(c, 1);
    } else {
       charCount.put(c, charCount.get(c) + 1);
    }
}

// Here you print the char count:
for (Entry<Integer, Integer> entry : charCount.entrySet()) {
    // (char) entry.getKey() is the character
    // entry.getValue() is number of occurence
}

没有Map

int[][] count = new int[MAX_CHAR][2];
for (int c : input.toCharArray()) {
    count[c][0] += 1; // Increase occurrence by 1
    count[c][1] = 1; // Mark this character exists in string
}
// Here you can print the count of char per character
// Not that, you can use count[c][1] to determine that if the character exists in your String
for (int i = 0; i < MAX_CHAR; i++) {
    if (count[i][1] == 1) {
        System.out.println("Char: " + (char) i + " Occurence: " + count[i][0]);
    }
}

编辑 正如@oreh 建议的那样,我们甚至不需要二维数组:

int[] count = new int[MAX_CHAR];
for (int c : input.toCharArray()) {
    count[c][0] += 1; // Increase occurrence by 1
}
for (int i = 0; i < MAX_CHAR; i++) {
    if (count[i] > 0) {
        System.out.println("Char: " + (char) i + " Occurence: " + count[i]);
    }
}

【讨论】:

  • 这个可以,但是老师说不用地图也可以。
  • 是的,当然。像您的想法一样使用您的阵列。像我一样做精确的循环,但使用数组来支持它
  • 使用 Map 是 26 个字母的开销。
  • @oleg.cherednik // Create an array of size 256 i.e. ASCII_SIZE 我认为它不受 26 个字符的限制
  • 是的,但是根据描述,我可以看到他只搜索字母。
【解决方案2】:

如果您只想找到例如字母,那么您知道 ASCII 码的范围。在这种情况下,使用一维数组并将索引表示为带有偏移量的符号代码就足够了。例如。要仅查找字母,您可以创建数组 int[] count = new int[26],并且 int total_a = count[0]; // or count['a' - 'a'] 包含 a 的计数器,对于字母 z,我们有最后一个索引:int total_z = count[25]; // or count['z' - 'a']

public static void printLetterOccurrence(String str) {
    int[] count = new int['z' - 'a' + 1];
    str = str.toLowerCase();

    for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
            count[str.charAt(i) - 'a']++;

    for (int i = 0; i < count.length; i++)
        if (count[i] > 0)
            System.out.println("Number of Occurrence of " + (char)('a' + i) + " is: " + count[i]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2022-01-17
    • 2017-09-24
    • 2011-06-14
    • 2018-05-07
    • 2022-01-03
    相关资源
    最近更新 更多