How do I replace a character in a string in Java?


The simple answer is:

token = token.replace("&", "&");

Despite the name as compared to replaceAll, replace does do a replaceAll, it just doesn't use a regular expression, which seems to be in order here (both from a performance and a good practice perspective - don't use regular expressions by accident as they have special character requirements which you won't be paying attention to).

Sean Bright's answer is probably as good as is worth thinking about from a performance perspective absent some further target requirement on performance and performance testing, if you already know this code is a hot spot for performance, if that is where your question is coming from. It certainly doesn't deserve the downvotes. Just use StringBuilder instead of StringBuffer unless you need the synchronization.

That being said, there is a somewhat deeper potential problem here. Escaping characters is a known problem which lots of libraries out there address. You may want to consider wrapping the data in a CDATA section in the XML, or you may prefer to use an XML library (including the one that comes with the JDK now) to actually generate the XML properly (so that it will handle the encoding).

Apache also has an escaping library as part of Commons Lang.


Using Java, I want to go through the lines of a text and replace all ampersand symbols (&) with the XML entity reference &.

I scan the lines of the text and then each word in the text with the Scanner class. Then I use the CharacterIterator to iterate over each characters of the word. However, how can I replace the character? First, Strings are immutable objects. Second, I want to replace a character (&) with several characters(amp&;). How should I approach this?

CharacterIterator it = new StringCharacterIterator(token);
for(char ch = it.first(); ch != CharacterIterator.DONE; ch = {
       if(ch == '&') {


Rename ä, ö, ü to ae, oe, ue

You can use the Unicode block property \p{InCombiningDiacriticalMarks} to remove (most) diacritical marks from Strings:

public String normalize(String input) {
  String output = Normalizer.normalize(input, Normalizer.Form.NFD); 
  Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");

  return pattern.matcher(output).replaceAll("");

This will not replace German umlauts the way you desire, though. It will turn ö into o, ä into a and so on. But maybe that's okay for you, too.

Use :

youraddress = youraddress.replaceAll("\\s", "+");
String uri = "" +
              youraddress + "&sensor=false";

Replace all spaces to +, similar to the way google does. This is how we are using in our apps.

Escape the backslash:

myString = myString.replace("\\x0d", "whateverYouWantToReplaceWith")

See it working on ideone.