replace String with another in java

前端 未结 6 1801
孤城傲影
孤城傲影 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:40

    Another suggestion, Let's say you have two same words in the String

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

    replace function will change every string is given in the first parameter to the second parameter

    System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
    

    and you can use also replaceAll method for the same result

    System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
    

    if you want to change just the first string which is positioned earlier,

    System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.
    

提交回复
热议问题