Domanda

I want to get the frequency of all 128 signs (ASCII) with the simplest code possible. No imports. I am writing in Java (Eclipse), starting off like this:

public class Text {
public static void main (String[] args) {

then I want to calculate the frequency of each sign with a loop (preferably for loop). I know how to do this for a specific sign, e.g. the sign 'a' which is 97:

int a = 0;
for (int i = 0; i < s.length(); i++) {             // s is a String
    if (s.charAt(i) == 'a') {
        a += 1;
    }
}
System.out.println("a: " + a);

I need to create a table of all the signs (e.g. int[] p = new int p[1,2,3] - only for a string (or char?)) assign each index its number and then let a loop write out all the sign frequencies. All this should be done only with loops and commands: .length, charAt().

È stato utile?

Soluzione

Simply:

final String s = "Hello World!";
final int frequencies[] = new int[128];

for (int i = 0; i < s.length(); i++) {
    final int ascii = (int) s.charAt(i);
    frequencies[ascii]++;
}

Altri suggerimenti

(in response to user2974951's "answer")

That's the String representation of the array. Try printing with a loop instead:

for(int i = 0; i < frequencies.length; i++) {
    System.out.println(frequencies[i]);
}

You can also try System.out.println(Arrays.toString(frequencies)); but that might look a bit ugly given the large amount of ASCII characters you are considering.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top