Posts

Showing posts from October, 2012

How to efficiently replace multiple characters in a Java String

The problem of string transformation and manipulation is so common that every programming language offers either special features about it or, at the very least, a standard library with basic solutions. In Java there's both regular expression matching /replacement via its standard library, and various “replace” operations that may be directly called on a String object. The replace operations return a new String, as in Java there can be no in-place replacement of String contents; String objects are immutable. One problem that is common enough, in my opinion, to justify the development of a special method to handle it is this: replacing multiple characters in a String at once (in one go). There are three kinds of replacements that we want to handle: Replacing a character with another single character. This kind of replacement does not affect the length of the original string. Replacing a single character with a sequence of characters (a string). This kind of replacement w