Checking string within string

5

How to tell if specific text is contained in a string ?

example:

String str = " Hello Word";

How do I check to see if the word "Hello" is contained in that string "str".

And if the check is true, how do you edit it?

If the word "Hello" in string "str" then the word "Hello" will be changed to "Hello"

    
asked by anonymous 16.07.2015 / 03:04

1 answer

11

To verify use the contains() and to change use replace() .

String str = " Hello Word";
if (str.contains("Hello")) {
    str = str.replace("Hello", "Olá"); //note que é necessário reatribuir a variável
}

Or optimized:

String str = " Hello Word";
str = str.replace("Hello", "Olá");

After all, if you do not have it, you will not make the exchange. I made the first one to fulfill what you requested, maybe want to know contains() .

    
16.07.2015 / 03:10