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

前端 未结 4 1499
甜味超标
甜味超标 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:44

    Below is the definition from Java docs for the overloaded replace method of your case.

    String java.lang.String.replace(CharSequence target, CharSequence replacement)

    Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

    Parameters:
    target The sequence of char values to be replaced
    replacement The replacement sequence of char values

    Now, since you are defining target value as "" i.e. empty, so it will pick each location in the string and replace it with value defined in replacement.

    Good thing to note is the fact that if you will use strSample = strSample.replace(" ","p"); which means one white space character as target value then nothing will be replaced because now in this case replace method will try to search for a white space character.

提交回复
热议问题