Checking string inside string

Asked

Viewed 149 times

5

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

example:

String str = " Hello Word";

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

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

In case there is the word "Hello" in string "str" then the word "Hello" will be changed to "Hello"

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

11

To check use the method contains() and to exchange use the 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á");

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

After all, if you don’t have it, you won’t make the switch. I made the first one to meet what you asked for, you might want to meet the contains().

  • Thank you, that’s exactly what I wanted :)

  • @Higorbarbosa better than thanks, the more correct is you accept the answer and vote for it (you can vote for everything on the site). See the [tour] to understand better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.