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

How would I make out the word "hello" in the sentence "hello, how are you?" or in parsing the word "how" to "how are you?"

An example of what I want in the 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"); } 
+4
source share
5 answers

To just find a substring, you can use contains or indexOf or any other option:

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 need word boundaries, then StringTokenizer is probably a good approach.

http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html

You can then perform case insensitive (equalsIgnoreCase) checks for each word.

+7
source

Looks like work for regular expressions . Contains will give a false positive value, say, "hire-purchase" .

 if (Pattern.match("\\bhi\\b", stringToMatch)) { //... 
+5
source

I would go for java.util.StringTokenizer : http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html

 StringTokenizer st = new StringTokenizer( "Hi, how are you?", ",.:?! \t\n\r" //whitespace and puntuation as delimiters ); while (st.hasMoreTokens()) { if(st.nextToken().equals("hi")){ //matches "hi" } } 

Alternatively take a look at java.util.regex and use regular expressions.

+3
source

I would choose a tokenizer . Set space and other elements such as commas, full stops, etc. As delimiters. And remember to compare case insensitive.

Thus, you can find โ€œhelloโ€ in โ€œHello, how does his test passโ€ without receiving a false positive result for โ€œhimโ€ and a false negative value for โ€œHelloโ€ (starts with an uppercase letter H).

0
source

You can pass the regular expression to the next() Scanner method. Thus, you can iterate over each word in the input file (by default, the separator of the scanner by space) and perform the corresponding processing if you get a match.

0
source

Source: https://habr.com/ru/post/1301969/


All Articles