Search code examples
javachars

Adding and representing chars with asterisk in java


I have this assignment where I need to create a program that reads the user input and reads the sentence and in the end it needs to represent the amount of times each char repeats itself with asterisk.

By this time this is all the code I have for this assignment:

    import java.util.Scanner;

    public class Chars {
public static void main (String[] args){
    Scanner teclado = new Scanner(System.in);
    System.out.println("insere um texto");
    String teutexto = teclado.nextLine();
    int a = 0;
    for(int x=0;x<teutexto.length();x++){
        if( String.charAt(0) == 'a'){

        }

    }

Solution

  • This is a simple way of doing it using bucket sort. You simply keep an array of integers for each character in the alphabet and increase them each time the character occurs in the input string.

    We know that (int)'a' = 97, (int)'b' = 98 etc. So a little trick to represent (a,b,...,z) as (0,1,...,25) is to set that for a given character ch that (int)(ch-'a'). Thus we subtract the value of ch with 97. For example: (int)('a'-'a') = 0 and (int)('z'-'a') = 25.

    Now we can easily make an array int[] occurrences = new int[26] where occurrences[i] will be the number of occurrences of the i-th character in the alphabet.

    For example in the string "aaab", after running the algorithm:

    occurrences[0] = 3 and occurrences[1] = 1.

    This is the same as

    occurrences['a'-'a'] = 3 and occurrences['b'-'a'] = 1

    If you understand this concept, you will see that we can simply loop through the input string and for each character ch we can just increase occurrences[ch-'a']++. This is the whole algorithm.

    Here is the full code:

    Scanner input = new Scanner(System.in);
    String str = input.nextLine().toLowerCase();
    
    int[] occurrences = new int[26];
    
    // go through all the characters in the input string
    for(char ch : str.toCharArray())
        if(ch >= 'a' && ch <= 'z') // 'ch' is a valid character in the alphabet
            occurrences[ch-'a']++; // increase the occurrence of 'ch'
    
    // go through the the alphabet
    for(int i = 0; i < 26; i++) {
        System.out.print((char)('a'+i) + ": "); // print the i-th character in the alphabet
        // occurrences[i] contains the number of occurrences of the i-th character
        for(int j = 0; j < occurrences[i]; j++)
            System.out.print("*"); // print '*' for every occurrance of the i-th character
        System.out.println(); // separate with new line
    }
    input.close(); // close scanner