Figgueh
Figgueh

Reputation: 35

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

This is the reference code:

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

The output is supposed to resemble:

Number of occurrence of 'x' is: 'times it occured'

If the letter has occurred previously then only display the occurrence once.


I get the logic using 2 for loops, although my teacher said its possible to execute this application using only 1 for loop.

the issue i'm running into is:
I'm able to find if the character has been already found only if they are beside each other.

How are you expected to check if all the previous character have been found without another for loop?

Upvotes: 0

Views: 4455

Answers (3)

Nisarg Patel
Nisarg Patel

Reputation: 1

 public static char getMax(String text) {
    int MAX_CHARS = 256;
    int curr_max = -1;
    char curr_max_char = '-';
    
    int count[] = new int[MAX_CHARS];
    int len = text.length();
    
    for(int i =0; i<len; i++ ) {
        count[text.charAt(i)]++;
        
        if(count[text.charAt(i)] > curr_max) {
            curr_max = count[text.charAt(i)]++;
            curr_max_char = text.charAt(i);
        }
    }
    
    return curr_max_char;
}

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

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

Upvotes: 0

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

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

Upvotes: 2

Related Questions