Anzahl bestimmter Zeichen in einer Zeichenkette (Java)

Ich habe eine Hausaufgabe zum zählen bestimmter Zeichen in der Zeichenfolge.

Beispiel: string = "America"

Sollte die Ausgabe = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time

public class switchbobo {

/**
 * @param args
 */     //TODO Auto-generated method stub
  public static void main(String[] args){
    String s = "BUNANA";
    String lower = s.toLowerCase();
    char[] c = lower.toCharArray(); //converting to a char array
    int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;

    for(int i = 0; i< c.length;i++) {
        if(c[i]=='a') //looking for 'a' only
          freq++;
        if(c[i]=='b')
          freq2++;
        if (c[i]=='c') {
          freq3++;
        }

        if (c[i]=='d') {
          freq4++;
        }       
    }
    System.out.println("Total chars "+c.length);
    if (freq > 0) {
      System.out.println("Number of 'a' are "+freq);
    }
  }
}

code oben ist, was ich getan habe, aber ich denke, es ist nicht sinnvoll, 26 Variablen (eine für jeden Buchstaben). Habt Ihr alternative Ergebnis?

  • Verwenden Sie ein array mit 26 die Indizes. ('a'-'a' == 0, 'b' - 'a' == 1, und so weiter und so Fort).
InformationsquelleAutor user1432513 | 2012-06-03
Schreibe einen Kommentar