Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search the whole string for a specific word?

Tags:

java

android

I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:

for (int i = 0; i < countryCode.length; i++) {
            if (textlength <= countryCode[i].length()) {
                if (etsearch
                        .getText()
                        .toString()
                        .equalsIgnoreCase(
                                (String) countryCode[i].subSequence(0,
                                        textlength))) {
                    text_sort.add(countryCode[i]);
                    image_sort.add(flag[i]);
                    condition_sort.add(condition[i]);
                }
            }
        }

But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?

like image 535
Reyjohn Avatar asked May 24 '12 15:05

Reyjohn


3 Answers

I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:

    b = string.indexOf("I am") >= 0; 
like image 64
Mr. Morris Avatar answered Oct 15 '22 09:10

Mr. Morris


You have three way to search if an string contain substring or not:

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")  ;             // true if contains but ignore case
like image 27
ρяσѕρєя K Avatar answered Oct 15 '22 08:10

ρяσѕρєя K


Check out the contains(CharSequence) method

like image 3
compuguru Avatar answered Oct 15 '22 09:10

compuguru