1

i want to check if the particular word is exits or not in the string with ignore case.

My String is - "Hello world , Wassup? , good moRNING".

Now i want to check if the word - "hello world".

so i have tried the following:

String fullText = "Hello world , Wassup? , good moRNING";
String singleWord = "hello world";
boolean find;

 if (fullText.matches(singleWord)) {

    find = True;
}

I have also tried with contains but this is not working.

How can i find this particular word ?

  • 1
    Try google and look here: http://stackoverflow.com/questions/5091057/how-to-find-a-whole-word-in-a-string-in-java – Flummox - don't be evil SE Dec 28 '16 at 10:03
  • 1
    hello and Hello is different – Aditya Vyas-Lakhan Dec 28 '16 at 10:04
  • Apart from the difference between lowercase and uppercase `h` (as @AdityaVyas-Lakhan pointed out), `contains()` should work. `matches()` is not suited since it (a) requires a regular expression and (b) only returns true if the entire string matches the regex, that is, doesn’t contain more characters before or after. – Ole V.V. Dec 28 '16 at 10:11
  • It’s an aside: `true` should be with a small `t` (can’t believe how many of the answers copied this error). – Ole V.V. Dec 28 '16 at 10:13

5 Answers5

3
find = fullText.toUpperCase().contains(singleWord.toUpperCase());
hzitoun
  • 5,492
  • 1
  • 36
  • 43
3

You can convert both string to common case and then make use of indexOf or otherwise with matched you need to make use of a regex.

String fullText = "Hello world , Wassup? , good moRNING";
String singleWord = "hello world";
boolean find;



if (fullText.toLowerCase().indexOf(singleWord.toLowerCase()) > -1) {

    find = true;
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

You can try lower casing both the sentence to be searched and the string, e.g.

if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
    find = True;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

you can try this :

String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0;         // true if contains 

// Anywhere in string
b = string.matches("(?i).*i am.*");     // true if contains but ignore case

// Anywhere in string
b = string.contains("AA")  ; 
Apoorv Mehrotra
  • 607
  • 5
  • 13
0

The problem is the case:

Hello world doesn't contains hello world because it has the capital letter.

Use this:

if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
  find = True;
}
Pier Giorgio Misley
  • 5,305
  • 4
  • 27
  • 66