Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- how to parse for words in a string for a specific word

How would I parse for the word "hi" in the sentence "hi, how are you?" or in parse for the word "how" in "how are you?"?

example of what I want in code:

String word = "hi";
String word2 = "how";
Scanner scan = new Scanner(System.in).useDelimiter("\n");
String s = scan.nextLine();
if(s.equals(word)) {
System.out.println("Hey");
}
if(s.equals(word2)) {
System.out.println("Hey");
}
like image 950
Jackson Curtis Avatar asked Dec 08 '22 04:12

Jackson Curtis


2 Answers

To just find the substring, you can use contains or indexOf or any other variant:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html

if( s.contains( word ) ) {
   // ...
}

if( s.indexOf( word2 ) >=0 ) {
   // ...
}

If you care about word boundaries, then StringTokenizer is probably a good approach.

https://docs.oracle.com/javase/1.5.0/docs/api/java/util/StringTokenizer.html

You can then perform a case-insensitive check (equalsIgnoreCase) on each word.

like image 107
Ryan Emerle Avatar answered Dec 09 '22 16:12

Ryan Emerle


Looks like a job for Regular Expressions. Contains would give a false positive on, say, "hire-purchase".

if (Pattern.match("\\bhi\\b", stringToMatch)) { //...
like image 28
Anon. Avatar answered Dec 09 '22 18:12

Anon.