Java中如何用另一个字符串替换字符串

106

有什么函数可以将一个字符串替换为另一个字符串?

示例1:如何将 "HelloBrother" 替换为 "Brother"

示例2:如何将 "JAVAISBEST" 替换为 "BEST"


2
你只想要最后一个单词吗? - SNR
7个回答

155
replace 方法是你要找的方法。
例如:
String replacedString = someString.replace("HelloBrother", "Brother");

49

6
几乎是因为分享一个旧版Javadocs的链接而被扣除了近-1分。 - Stephen C

11

有可能不使用额外的变量

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);

1
这并不是一个新的答案,而是对@DeadProgrammer答案的改进。 - Kalle Richter
这是现有的答案,请尝试使用不同的方法 @oleg sh - Lova Chittumuri

8

可以通过以下方法将一个字符串替换为另一个字符串

方法1:使用字符串 replaceAll

 String myInput = "HelloBrother";
 String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
 ---OR---
 String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
 System.out.println("My Output is : " +myOutput);       

Method 2: Using Pattern.compile

 import java.util.regex.Pattern;
 String myInput = "JAVAISBEST";
 String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
 ---OR -----
 String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
 System.out.println("My Output is : " +myOutputWithRegEX);           

方法3:使用如下链接中定义的Apache Commons

http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)

REFERENCE


6
     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

0
你可以使用replace方法来实现这个功能:
String outputString1 = inputString.replace("HelloBrother", "Brother");
String outputString2 = inputString.replace("JAVAISBEST", "BEST");

0
另一个建议, 假设您在字符串中有两个相同的单词。
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.

replace函数将会把第一个参数中的每个字符串替换为第二个参数

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

你也可以使用replaceAll方法来获得相同的结果

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

如果你想要更改位于前面的第一个字符串,

System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接