Difficulty with nested loop and text

edited July 2015 in Questions about Code

Hello, I am trying to figure out how to do the following:

  • Check first character in a string
  • Check what that character is.
  • Add 1 to counter (could use an array to store the frequency of each character)
  • Move on to the next character in the string
  • and so on..

Essentially I am trying to figure out a way of counting the frequency of each different character in a string.

I was able to do this using if/else statements for each letter of the alphabet but ideally I would like a better way of doing this.

Heres what I have so far:

      String yourString = msg;
      char[] allChars = new char[yourString.length()];
      for (int i = 0; i < yourString.length (); i++) {
        allChars[i] = yourString.charAt(i);
        String character = str(allChars[i]);

        for (counter=0; counter < alpha.length; counter++) {
          if (character.equals(alpha[counter]) == true ) {
            count[counter] = count[counter]+1;
          }
        }
      println("The number of A is" + count[0]);
      }

alpha is a character array containing the individual letters of the alphabet count is an array where I am trying to store the values i.e:

  • count[0] would equal the number of times the letter A appears in the string
  • count[1] would equal the number of times the letter B appears in the string

Any help would be great! thanks!

Answers

  • edited July 2015 Answer ✓
    // forum.Processing.org/two/discussion/11801/difficulty-with-nested-loop-and-text
    // 2015-Jul-22
    
    static final String TXT = "Difficulty with nested loop and text.";
    final int[] letters = new int['Z' - 'A' + 1];
    
    void setup() {
      println(TXT, '\n');
      displayLetterCount(countLetters(letters, TXT));
      exit();
    }
    
    static final int[] clearLetterCount(int[] alpha) {
      java.util.Arrays.fill(alpha, 0);
      return alpha;
    }
    
    static final int[] countLetters(int[] alpha, String txt) {
      clearLetterCount(alpha);
    
      for (char c : txt.toUpperCase().toCharArray()) {
        int idx = c - 'A';
        if (idx >= 0 & idx < alpha.length)  ++alpha[idx];
      }
    
      return alpha;
    }
    
    static final int[] displayLetterCount(int[] alpha) {
      for (int i = 0; i != alpha.length
        ; print(char(i + 'A') + ":", alpha[i++], '\t'));
    
      return alpha;
    }
    
Sign In or Register to comment.