Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - Count letters in a string

I need to find an algorithm which counts the letters in any string (e.g. "cabababb") and the output must be in a alphabetical manner(e.g. a: 3, b: 4, c:1 etc.) . There is no need to distinguish between upper and lower case letters. I am not allowed to youse a HashMap.

This is my code till now: I'ts not working, I think I've got the wrong strategy here. Can you help me please?

public class Stringray extends MiniJava{
public static void main(String[] args) {
    // Texteingabe
    String input = readString("Geben Sie einen Text ein: ");

    String output = "";
    int i = 0;

    // H?ufigkeit der Buchstaben
    int count = 0;
    char letter = 'a';
    while(i < input.length()) {
            while(i < input.length()) {
                if(input.charAt(i) == letter) {
                    while(i < input.length()) {
                        count++;
                        i++;
                    }
                    output = output + letter + ": " + count + "	";
                }
                i++;
            }
            letter++;
    }
    write(output);
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a simple algorithm:

  1. Create an empty int[] array of length 26, it will be initialized with 0s
  2. Iterate your String
  3. Get the char at the current index.
  4. Tricky part: You need a mapping between a given char and its corresponding index (e.g. a would be index 0, b would be index 1 and so on). Have a look at an ASCII-Table for this
  5. Add 1 to the element at the mapped index of the created array.
  6. At the end, iterate the array and only print the values that are not 0 along with the corresponding char at that index (Need the ASCII mapping again here)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...