Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 value of String.replace("","");

so on Testing I came to a condition of replacing blank value with some other value i.e String.replace("","p") which replaced "p" everywhere around all the characters of the original String

Example:

String strSample = "val";
strSample = strSample.replace("","p");
System.out.println(strSample);

Output:

pvpaplp

Can anyone please explain why it works like this?

like image 679
user5612655 Avatar asked Nov 22 '25 08:11

user5612655


1 Answers

replace looks for each place that you have a String which starts with the replaced string. e.g. if you replace "a" in "banana" it finds "a" 3 times.

However, for empty string it finds it everywhere including before and after the last letter.

like image 99
Peter Lawrey Avatar answered Nov 23 '25 22:11

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!