How to make sketch look through string + make a println showing number of occurrences of each vowel?

I need to make the sketch search through the string "The unusually quick brown fox jumps over the lazy family dog repeatedly." and make a (println) output report showing the number of occurrences for each vowel (a,e,i,o,u). I made some code, but I got stuck. For example, the println showed 9 for the vowel a even though the vowel a occurs four times in the string. What am I doing wrong? Thanks.

String sentence = "The unusually quick brown fox jumps over the lazy family dog repeatedly.";
println(sentence.indexOf("a"));
println(sentence.indexOf("e"));
println(sentence.indexOf("i"));
println(sentence.indexOf("o"));
println(sentence.indexOf("u"));
noLoop();

Answers

  • indexOf() gives you the position of the first instance of the search term in the string, starting at zero... So it's not what you want.

  • You could use matchAll. Since this is obviously homework I'll leave you to figure it out ;)

  • edited December 2015
    // forum.Processing.org/two/discussion/13750/
    // how-to-make-sketch-look-through-string-
    // make-a-println-showing-number-of-occurrences-of-each-vowel
    
    // GoToLoop (2015-Dec-02)
    
    static final int getVowelValue(char ch) {
      switch (ch) {
        case 'a': return 0;
        case 'e': return 1;
        case 'i': return 2;
        case 'o': return 3;
        case 'u': return 4;
        default:  return -1;
      }
    }
    
    static final String SENTENCE = 
      "The unusually quick brown fox " +
      "jumps over the lazy family dog repeatedly.";
    
    final int[] vowels = new int[5];
    
    void setup() {
      for (char ch : SENTENCE.toLowerCase().toCharArray()) {
        int idx = getVowelValue(ch);
        if (idx >= 0 & idx < vowels.length)  ++vowels[idx];
      }
    
      printArray(vowels);
      exit();
    }
    
  • Answer ✓

    Pretty much the same question was asked some days ago: https://forum.processing.org/two/discussion/13665/how-to-count-the-repeated-alphabet-in-sketch

    The link i posted has some good proposals.

Sign In or Register to comment.