Search code examples
javasearchcomparecontainsmatcher

how to search for keywords in strings


I need to do some keywords search and print if true. works fine if i am comparing in order. but i want to

compare the following cases and expect them to be true.

do some java programming = true

some java = true

do programming = true

and finally most importantly

programming java = true

programming java some do = true

I need to return true for all the cases mentioned above but so far it only works for case 1 and 2

public class Examples {

    public static void main(String[] args) {
        String[] given = new String[20];
        given[0]  = ("do some java programming");
        given[1] = ("do some grocery shopping");
        given[2] = ("play soccer at the west field");
        String input = new String();
        Scanner userInput = new Scanner(System.in);

        System.out.println("Enter the string to compare");
        input[0] = userInput.nextLine();
        for (int i=0; i <20; i++){
        if(given[i].contains(input))
        {
            System.out.println(given[i]);
        }
        else
        {
            //do nothing
        }
        }
    }
}

Solution

  • For this Regex will be your friend.

    Here's some working code to play with:

    String[] matches = input[0].split(" ");           
    for (int i=0; i <3; i++){
      for(String s: matches){
        if(given[i].contains(s))
          System.out.println(given[i]);
          break;
         }      
      }
    }