用java中的另一个replacestring

什么函数可以用另一个stringreplacestring?

Example#1:什么将"Brother"replace为"HelloBrother" "Brother"

例#2:什么将"JAVAISBEST"replace为"BEST"

replace方法是你在找什么。

例如:

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

试试这个: http : //download.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29

 String a = "HelloBrother How are you!"; String r = a.replace("HelloBrother","Brother"); print.i(r); 

这会打印出“兄弟,你好吗”!

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

replace一个string可以在下面的方法中完成

方法1:使用stringreplaceAll

  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) 

参考

有可能不使用额外的variables

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