kishore
kishore

Reputation: 25

What method should I use to replace text within a String

I have the following string:

str = "kishore kumar venkata"

I want to replace this string with "kishore tamire venkata".

What are the string methods used for this? Can someone explain the procedure for replacing?

Upvotes: 0

Views: 165

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170308

For simple replacements, you can use String.replace(...), as Péter already suggested. However, be aware that replace(...) also causes the substring kumar to be replaced in the string:

"kishore kumaraa venkata"
         ^^^^^

if you don't want that to happen, you could use the String.replaceAll(...) and provide the regex pattern:

\bkumar\b

where \b denotes a word boundary.

A demo:

String str = "kishore kumaraa kumar venkata";
String rep = str.replaceAll("\\bkumar\\b", "tamire");
System.out.println(str+"\n"+rep);

will print:

kishore kumaraa kumar venkata
kishore kumaraa tamire venkata

Upvotes: 1

Péter Török
Péter Török

Reputation: 116306

The method to use is (hardly surprising) String.replace:

str = str.replace("kumar", "tamire");

Note that as String is immutable, the original string is not changed, and the method returns the modified string instead.

Upvotes: 3

Related Questions