有什么函数可以将一个字符串替换为另一个字符串?
示例1:如何将 "HelloBrother"
替换为 "Brother"
?
示例2:如何将 "JAVAISBEST"
替换为 "BEST"
?
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
有可能不使用额外的变量
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
可以通过以下方法将一个字符串替换为另一个字符串
方法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)
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
String outputString1 = inputString.replace("HelloBrother", "Brother");
String outputString2 = inputString.replace("JAVAISBEST", "BEST");
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.