replace String with another in java

前端 未结 6 1800
孤城傲影
孤城傲影 2020-11-22 08:14

What function can replace a string with another string?

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

Example #2

6条回答
  •  滥情空心
    2020-11-22 08:37

    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

提交回复
热议问题