Replace with empty string replaces newChar around all the characters in original string

前端 未结 4 1604
甜味超标
甜味超标 2021-01-20 07:13

I was just working on one of my java code in which I am using Java String.replace method. So while testing the replace method as in one situation I am planning to put junk v

4条回答
  •  天命终不由人
    2021-01-20 07:50

    Take a look at this example:

    "" + "abc" + ""
    

    What is result of this code?
    Answer: it is still "abc". So as you see we can say that all strings have some empty strings before and after it.

    Same rule applies in-between characters like

    "a"+""+"b"+""+"c"
    

    will still create "abc"

    So empty strings also exists between characters.

    In your code

    "val".replace("","p")
    

    all these empty strings ware replaced with p which result in pvpaplp.


    In case of ""+""+..+""+"" assume that Java is smart enough to see it as one "".

提交回复
热议问题