开发者

What method should I use to replace text within a String

I have the following string:

str 开发者_StackOverflow中文版= "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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜