【问题标题】:replace String with another in java在java中用另一个替换String
【发布时间】:2011-07-10 03:09:55
【问题描述】:

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

示例 #1:什么将 "HelloBrother" 替换为 "Brother"

示例 #2:什么将 "JAVAISBEST" 替换为 "BEST"

【问题讨论】:

  • 所以你只想要最后一句话?

标签: java string


【解决方案1】:

replace 方法正是您想要的。

例如:

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

【讨论】:

    【解决方案2】:

    试试这个: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

    String a = "HelloBrother How are you!";
    String r = a.replace("HelloBrother","Brother");
    
    System.out.println(r);
    

    这会打印出“Brother How are you!”

    【讨论】:

    • 几乎 -1 用于提供指向 javadocs 的古代副本的链接。
    【解决方案3】:

    有可能不使用额外的变量

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

    【讨论】:

    • 这不是一个新的答案,而是@DeadProgrammer 的答案的改进。
    • 这是现有答案,请尝试不同的方法@oleg sh
    【解决方案4】:

    可以通过以下方法将一个字符串替换为另一个字符串

    方法一:使用字符串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);       
    

    方法二:使用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)
    

    REFERENCE

    【讨论】:

      【解决方案5】:
           String s1 = "HelloSuresh";
           String m = s1.replace("Hello","");
           System.out.println(m);
      

      【讨论】:

        【解决方案6】:

        另一个建议, 假设您在字符串中有两个相同的单词

        String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
        

        替换函数会将第一个参数中给出的每个字符串更改为第二个参数

        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.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-07
          • 2016-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-06
          相关资源
          最近更新 更多