Question regarding indexOf

indexOf returns the index position of the first occurrence of a substring, is it possible to return all of the occurrences of a substring (character) in the same way?

Answers

  • You can write your own function to do this. Just start searching again using the optional fromIndex parameter, which should be one more than the last result. Just keep finding more matches until you get a -1 match, which means there's no more.

    https://processing.org/reference/String_indexOf_.html

  • hmm I am not really sure I understand your solution, at the moment i am using indexOf in order to look for vowels from Strings(sentences), and when a vowel is found, an action is triggered, but indexOf only finds the first occurrence

  • Answer ✓
    String str = "Cat Hat Mat Flat Bat";
    
    void matcher(String in, String find){
      int index = 0;
      int last = -1;
      while(index != -1){
        index = in.indexOf(find, last+1);
        if( index != -1 ){
          println(index);
          last = index;
        }
      }
    }
    
    void setup(){
      size(200,200);
      matcher(str, "at");  
      exit();
    }
    void draw(){}
    
  • Thank you sir!

Sign In or Register to comment.