count occurrence of a character in a given string using one for loop with java

count occurrence of a character in a given string using one for loop with java

Use a Map<Integer, Integer> (Key: Character, Value: Character count) to store your character count.

You only need to loop over your characters once:

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
}

Without 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]);
    }
}

Edit
As @oreh suggest, we dont even need a two dimension arrays:

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]);
    }
}

In case if you want to find e.g only letters, then you know the range of ASCII codes. In this case, it is enough to use 1D array and represend an index as symbol code with offset. E.g. to find only letters, you are able to create array int[] count = new int[26], and int total_a = count[0]; // or count[a - a] contains counter for a, and for leter z we have last index: 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]);
}

count occurrence of a character in a given string using one for loop with java

Leave a Reply

Your email address will not be published. Required fields are marked *