在java中用另一个替换String

Sha*_*hah 95 java string

什么函数可以用另一个字符串替换字符串?

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

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

pwc*_*pwc 143

这个replace方法就是你要找的.

例如:

String replacedString = someString.replace("HelloBrother", "Brother");
Run Code Online (Sandbox Code Playgroud)


Pro*_*cas 45

试试这个: 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");

System.out.println(r);
Run Code Online (Sandbox Code Playgroud)

这会打印出"兄弟你好!"

  • 几乎为-1,给出了一个古代javadocs副本的链接. (6认同)

Ole*_* SH 10

有可能不使用额外的变量

String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)


Nis*_*hia 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);       
Run Code Online (Sandbox Code Playgroud)

方法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);           
Run Code Online (Sandbox Code Playgroud)

方法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)
Run Code Online (Sandbox Code Playgroud)

参考


Dea*_*mer 5

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);
Run Code Online (Sandbox Code Playgroud)