How to replace characters in a java String?

Posted by ManBugra on Stack Overflow See other posts from Stack Overflow or by ManBugra
Published on 2010-04-16T14:37:44Z Indexed on 2010/04/16 14:43 UTC
Read the original article Hit count: 298

Filed under:
|

I like to replace a certain set of characters of a string with a corresponding replacement character in an efficent way.

For example:

String sourceCharacters = "šdccŠÐCCžŽ";
String targetCharacters = "sdccSDCCzZ";

String result = replaceChars("Gracišce", sourceCharacters , targetCharacters );

Assert.equals(result,"Gracisce") == true;

Is there are more efficient way than to use the replaceAll method of the String class?

My first idea was:

final String s = "Gracišce";
String sourceCharacters = "šdccŠÐCCžŽ";
String targetCharacters = "sdccSDCCzZ";

// preparation
final char[] sourceString = s.toCharArray();
final char result[] = new char[sourceString.length];
final char[] targetCharactersArray = targetCharacters.toCharArray();

// main work
for(int i=0,l=sourceString.length;i<l;++i)
{
  final int pos = sourceCharacters.indexOf(sourceString[i]);
  result[i] = pos!=-1 ? targetCharactersArray[pos] : sourceString[i];
}

// result
String resultString = new String(result);

Any ideas?

Btw, the UTF-8 characters are causing the trouble, with US_ASCII it works fine.

© Stack Overflow or respective owner

Related posts about java

Related posts about string-manipulation