Loading...
Logo
Processing Forum
I created an array of unwanted words and want to use match to iterate through and see if the string contains any of those keywords. Problem is, I keep getting some of the unwanted words show up. Please help.

Copy code
  1. String msg = "The colors of the rainbow";
  2. String[] filter = {"orange", "yellow", "green"};

  3.     for (int f = 0; f < filter.length; f++) { 
  4.       if(matchAll(msg, filter[f]) == null) {
  5. //some code here
  6. }
  7. }

Replies(3)



or use


Copy code
  1. if (msg.indexOf( filter[f] ) == -1) {
  2.    // contains it not
  3. }

But when you have it in a separate function named "string contains any of those unwanted keywords" you have to use return correctly. So only when the for-loop has ended fully and not one occurance has been found you can be sure that the string doesn't contain any of those unwanted keywords.
So only after the loop you have your result.

Copy code
  1. boolean stringcontainsanyofthoseunwantedkeywords (String msg) {
  2.     for (int f = 0; f < filter.length; f++) { 
  3.       if (msg.indexOf( filter[f] ) > -1) {
  4.           //some code here: one word found
  5.          return true;
  6. } // if
  7. } // for 
  8. // when he gets here, for-loop is done, no word has been found
  9. return false;
  10. } // func

Another way is to use a boolean var:

Copy code
  1. boolean stringcontainsanyofthoseunwantedkeywords (String msg) {

  2.     boolean containsIt = false;   // default

  3.     for (int f = 0; f < filter.length; f++) { 
  4.       if (msg.indexOf( filter[f] ) > -1) {
  5.           //some code here: one word found
  6.           containsIt = true; // can only become true, never false again in the for-loop
  7.       } // if
  8.    } // for

  9. // when he gets here, for-loop is done
  10. return containsIt; 

  11. } // func




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



Greetings, Chrisir   




you're welcome!