0

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 &amps; to replace.
 ArrayList<String> amps = new ArrayList<String>();
 String res = initial;
 int index = initial.indexOf("&amp;");
 // Get all the indexes of &amp.
 while (index >= 0) 
 {
 StringBuilder stb = new StringBuilder("&amp;");
 // Create a String until the next ";", for example &amp;#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("&amp;", 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

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

3 Comments

Oops.. that's right, I momentarily forgot about that. Thanks a lot.
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.
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.