用Java中的另一个替换String


97

什么功能可以用另一个字符串替换一个字符串?

实例1:将替代哪些"HelloBrother""Brother"

例2:将替代哪些"JAVAISBEST""BEST"


2
因此,您只想要最后一句话?
SNR

Answers:


147

replace方法是您要寻找的。

例如:

String replacedString = someString.replace("HelloBrother", "Brother");


10

有可能不使用额外的变量

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

1
这不是一个新的答案,而是@DeadProgrammer答案的改进。
卡尔·里希特

这是现有答案,请尝试使用不同的方法@oleg sh
Lova Chittumuri,

7

可以通过以下方法完成将一个字符串替换为另一个字符串的操作

方法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);       

方法2:使用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)

参考


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

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.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.