replace String with another in java

2018-12-31 18:44发布

问题:

What function can replace a string with another string?

Example #1: What will replace \"HelloBrother\" with \"Brother\"?

Example #2: What will replace \"JAVAISBEST\" with \"BEST\"?

回答1:

The replace method is what you\'re looking for.

For example:

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


回答2:

Try this: 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);

This would print out \"Brother How are you!\"



回答3:

There is a possibility not to use extra variables

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


回答4:

Replacing one string with another can be done in the below methods

Method 1: Using String 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);           

Method 3: Using Apache Commons as defined in the link below:

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



回答5:

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


标签: java string