1

You guys will probably laugh at the way that I implemented this simple task. I know there is a simpler way of doing this but I just really cant think of it right now. Can you guys please help me out?

String sample = "hello world";
char arraysample[] = sample.toCharArray();
int length = sample.length();

//count the number of each letter in the string
int acount = 0;
int bcount = 0;
int ccount = 0;
int dcount = 0;
int ecount = 0;
int fcount = 0;
int gcount = 0;
int hcount = 0;
int icount = 0;
int jcount = 0;
int kcount = 0;
int lcount = 0;
int mcount = 0;
int ncount = 0;
int ocount = 0;
int pcount = 0;
int qcount = 0;
int rcount = 0;
int scount = 0;
int tcount = 0;
int ucount = 0;
int vcount = 0;
int wcount = 0;
int xcount = 0;
int ycount = 0;
int zcount = 0;

for (int i = 0; i < length; i++) {
    char c = arraysample[i];
    switch (c) {
        case 'a':
            acount++;
            break;
        case 'b':
            bcount++;
            break;
        case 'c':
            ccount++;
            break;
        case 'd':
            dcount++;
            break;
        case 'e':
            ecount++;
            break;
        case 'f':
            fcount++;
            break;
        case 'g':
            gcount++;
            break;
        case 'h':
            hcount++;
            break;
        case 'i':
            icount++;
            break;
        case 'j':
            jcount++;
            break;
        case 'k':
            kcount++;
            break;
        case 'l':
            lcount++;
            break;
        case 'm':
            mcount++;
            break;
        case 'n':
            ncount++;
            break;
        case 'o':
            ocount++;
            break;
        case 'p':
            pcount++;
            break;
        case 'q':
            qcount++;
            break;
        case 'r':
            rcount++;
            break;
        case 's':
            scount++;
            break;
        case 't':
            tcount++;
            break;
        case 'u':
            ucount++;
            break;
        case 'v':
            vcount++;
            break;
        case 'w':
            wcount++;
            break;
        case 'x':
            xcount++;
            break;
        case 'y':
            ycount++;
            break;
        case 'z':
            zcount++;
            break;
    }
}

System.out.println("There are " + hcount + " h's in here ");
System.out.println("There are " + ocount + " o's in here ");
Tiny
  • 27,221
  • 105
  • 339
  • 599
statius
  • 33
  • 5

5 Answers5

3

Try using an array that uses the ASCII-code:

int[] counters = new int[0x100];
for(int i = 0; i < string.length(); i++) {
    char c = string.charAt(i);
    counters[(int) c]++;
}
for(char c = 'a'; c <= 'z'; c++) {
    System.out.println("There are "+counters[(int) c]+" "+c+"'s in the String.");
}

What you do is you fetch the right character (as you already did). Now every character has a number. You can look them up here: https://en.wikipedia.org/wiki/ASCII. And you increment the associated counter.

Some notes (as a response on Chuck Lowery's comment)

  • 0x100 is a hexadecimal number equal to 256 the number of possible characters.
  • The datastructure is a simple array. This allows fast access and increment. Although some characters are perhaps not interesting, the memory overhead negligable.

See the jdoodle.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

You could make a function that would use a regular expression to extract the string containing a concatenation of all the occurences of a given letter given as parameter and return the length of that string.

EDIT: the following page might also prove helpful: Java: How do I count the number of occurrences of a char in a String?

EDIT #2: Of course the good thing about your approach is that you only loop through the string once.

Community
  • 1
  • 1
Tonio
  • 414
  • 5
  • 17
0
public void countChars(String str) {
    int numOfChars = 'z' - 'a' + 1;
    int[] arr = new int[numOfChars];
    for (int i = 0; i < str.length(); i++) {
        arr[str.charAt(i) - 'a']++;
    }
    System.out.println("There are " + arr['z' - 'a'] + " z's in here ");
}
Hersh
  • 630
  • 4
  • 16
0

Use an array where the index corresponds to each character

String str = "Hello World";
String strLower = str.toLowerCase();

int[] charCounts = new int[26];

for (int i = 0; i < strLower.length(); i++) {
  char c = strLower.charAt(i);
  int charIndex = (int)c - 97
  charCounts[charIndex]++;
}
Brian
  • 7,098
  • 15
  • 56
  • 73
0

You should store the 'count' in a single container. In this case I think a Map would be most appropriate. Using a map you store a piece of information based on a Key : Value pair of any Object. In this case your Key could be the character (char type), like 'a' or 'z', and your Value would be the tally of that character (int type). You can read more about Maps in the Java API here.

An example implementation would be

Map m = new Map();
m.put('c',11);  //this puts the Value eleven into the map for Key 'c'
m.get('c');   //this would return the value stored for char 'c', in this case 11

If you are more comfortable using Arrays, you could store each char value so that the index of 'a' count is [0], the index of 'b' count is [ 1]. Or you could index the array by the ASCII value of each character, try something like char ch = (int)'a'; which should return 97.

  • This will indeed work, although I guess the `HashMap` (`Map` is an interface), will create a large amount of overhead. Furthermore it is even possible that the memory overhead will be larger (as a `HashMap` stores the keys and some kind of `LinkedList` as well). – Willem Van Onsem Mar 13 '14 at 00:48