Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace characters in a java String?

Tags:

java

string

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 = "šđćčŠĐĆČžŽ";
String targetCharacters = "sdccSDCCzZ";

String result = replaceChars("Gračišće", 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 = "Gračišće";
String sourceCharacters = "šđćčŠĐĆČžŽ";
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.

like image 876
ManBugra Avatar asked Apr 16 '10 14:04

ManBugra


1 Answers

You can make use of java.text.Normalizer and a shot of regex to get rid of the diacritics of which there exist much more than you have collected as far.

Here's an SSCCE, copy'n'paste'n'run it on Java 6:

package com.stackoverflow.q2653739;

import java.text.Normalizer;
import java.text.Normalizer.Form;

public class Test {

    public static void main(String... args) {
        System.out.println(removeDiacriticalMarks("Gračišće"));
    }

    public static String removeDiacriticalMarks(String string) {
        return Normalizer.normalize(string, Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
    }
}

This should yield

Gracisce

At least, it does here at Eclipse with console character encoding set to UTF-8 (Window > Preferences > General > Workspace > Text File Encoding). Ensure that the same is set in your environment as well.

As an alternative, maintain a Map<Character, Character>:

Map<Character, Character> charReplacementMap = new HashMap<Character, Character>();
charReplacementMap.put('š', 's');
charReplacementMap.put('đ', 'd');
// Put more here.

String originalString = "Gračišće";
StringBuilder builder = new StringBuilder();

for (char currentChar : originalString.toCharArray()) {
    Character replacementChar = charReplacementMap.get(currentChar);
    builder.append(replacementChar != null ? replacementChar : currentChar);
}

String newString = builder.toString();
like image 58
BalusC Avatar answered Oct 22 '22 11:10

BalusC