0

I am trying to search through a sentence and return it if it contains the specific "keyword" but atm it only work if the search is exactly the same as the message, so if the sentence is "hello my name is ben" then the search wont work with only "ben" or "hello" but I would have to use "hello my name is ben" for it to display, How would I get this to work. Thanks

public ArrayList<Message> getMessageByKeyword(String messageBody){
    ArrayList<Message> keyword = new ArrayList<>();

    for( Message p : this.myMessages)
        if( p.getMessageBody() == messageBody)
        {
            keyword.add( p );
        }

    return keyword;      
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Dec 04 '16 at 22:56
  • I am no trying to compare if the strings are the same, Im just trying to see if the string im searching for is inside the sentence, im not trying to check if they are the same – Serbian Guru Dec 04 '16 at 23:01
  • Then perhaps you'll want to use the `String#contains(...)` method. But one thing is for certain -- don't use `==`. – Hovercraft Full Of Eels Dec 04 '16 at 23:03
  • Have you looked at the [String API](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html) yet? That probably has all you need to solve this problem. – Hovercraft Full Of Eels Dec 04 '16 at 23:03
  • Thanks for the help, Ill look at it – Serbian Guru Dec 04 '16 at 23:05
  • I got it working using the String#contains(...) thanks again – Serbian Guru Dec 04 '16 at 23:15

0 Answers0