As I get an HTML file containing some wild chars like ⋍ or 𖫻, I want to replace them with a bullet. So I wrote this method :
public String replaceAmps(String initial)
{
// This list will contain all the &s; to replace.
ArrayList<String> amps = new ArrayList<String>();
String res = initial;
int index = initial.indexOf("&");
// Get all the indexes of &.
while (index >= 0)
{
StringBuilder stb = new StringBuilder("&");
// Create a String until the next ";", for example &#1091;<- this one
for(int i = index+5 ; initial.charAt(i) != ';' ; i++) stb.append(initial.charAt(i));
stb.append(";");
// Add the amp if needed in the list.
if(!amps.contains(stb.toString())) amps.add(stb.toString());
index = initial.indexOf("&", index + 1);
}
// Replace the Strings from the list with a bullet.
for(String s : amps) res.replace(s, "•");
return res;
}
I correctly get all the amps in my list, but the replacing doesn't work. Why? Thanks for your help.
asked Mar 19, 2013 at 23:37
Rob
16k22 gold badges73 silver badges110 bronze badges
1 Answer 1
Strings are immutable; the replace method returns a new String as the result of the replacement and does not modify res. Try
for(String s : amps) res = res.replace(s, "•");
answered Mar 19, 2013 at 23:39
rgettman
179k30 gold badges282 silver badges365 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Rob
Oops.. that's right, I momentarily forgot about that. Thanks a lot.
Mel Nicholson
It would probably be better to keep one StringBuilder for the final product. Since you don't care what the character to replace is, the loop body is just to append the unchanged part
substring(oldIndex, newIndex) append a bullet, then advance oldIndex to just past the semi-colon. DOn't forget to append the tail at the end.Dexygen
This has bitten me in the butt so many times, I've googled two times in the past week and this answer has come to the rescue, thanks
lang-java