如何替换java String中的字符?

时间:2010-04-16 14:37:45

标签: java string

我喜欢以有效的方式用相应的替换字符替换字符串的某组字符。

例如:

String sourceCharacters = "šđćčŠĐĆČžŽ";
String targetCharacters = "sdccSDCCzZ";

String result = replaceChars("Gračišće", sourceCharacters , targetCharacters );

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

是否有比使用String类的replaceAll方法更有效的方法?

我的第一个想法是:

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);

有什么想法吗?

顺便说一下,UTF-8字符造成了麻烦,US_ASCII可以正常使用。

2 个答案:

答案 0 :(得分:14)

你可以利用java.text.Normalizer和正则表达式来摆脱目前已经收集的diacritics

这是一个SSCCE,copy'n'paste'n'run它在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}+", "");
    }
}

这应该产生

Gracisce

至少,它在Eclipse中将控制台字符编码设置为UTF-8( Window&gt; Preferences&gt; General&gt; Workspace&gt; Text File Encoding )。确保在您的环境中也设置了相同的内容。

作为替代方案,请维护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();

答案 1 :(得分:0)

我在一个简单的循环中使用replace方法。

String sourceCharacters = "šđćčŠĐĆČžŽ";
String targetCharacters = "sdccSDCCzZ";

String s = "Gračišće";
for (int i=0 ; i<sourceCharacters.length() ; i++)
    s = s.replace(sourceCharacters.charAt[i], targetCharacters.charAt[i]);

System.out.println(s);