用一个字符串替换另一个字符串?

时间:2014-05-03 00:36:45

标签: java string unicode

如何用字母替换字符串中的字母,例如“Hello”?

String bubbled = "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ";

我最初只是在做一个replaceAll(“a”,“ⓐ”),但我觉得必须有一个更有效的方法来做到这一点。

4 个答案:

答案 0 :(得分:3)

bubbled拆分为小写和大写。制作一个新的StringBuilder,迭代每个来源字符,如果chr >= 'a' && chr <= 'z'追加lowercaseBubbled[chr - 'a'],如果它在大写字母范围内做类似,则只需附加chr 。最后,在构建器上使用toString

或者您可以使用效率稍低的方法,replaceChars(因为它必须使用indexOf)在Apache Commons中找到。亲:它是一个图书馆,所以没有额外的工作。

答案 1 :(得分:2)

这是一个代码snipp。它不会创建一个zillion String对象。我只有一小组泡泡字符仅用于演示目的。请根据自己的喜好进行调整,并且没有进行任何错误处理。

public class StackOverFlow {
    private static int[] bubbled = {'ⓐ', 'ⓑ', 'ⓒ', 'ⓓ', 'ⓔ'};
    private static int [] plain = {'a', 'b', 'c', 'd', 'e'};

    private static Map<Integer, Integer> charMap = new HashMap<>();

    public static void main(String[] args) {
        String test = "adcbbceead";
        for(int i=0; i<plain.length; i++) {
            charMap.put(plain[i], bubbled[i]);
        }
        replaceWithBuffer(test);
    }

    private static void replaceWithBuffer(String test) {
        System.out.println("Oginal String = " + test);
        StringBuilder sb = new StringBuilder(test);

        for(int i =0; i<test.length(); i++) {
            int ch = sb.charAt(i);
            char buubledChar = (char)charMap.get(ch).intValue();
            sb.setCharAt(i, buubledChar);
        }
        System.out.println("New String = " + sb.toString());
    }
}

<强>输出:

enter image description here

希望这会有所帮助:)

答案 2 :(得分:2)

您可以使用字符a来确定字母表的偏移值。结合StringBuilder它应该是相当有效的。当然,您可能必须对输入字符串只有字母字符非常严格。

这是我上面描述的代码:

public class Bubbled {
    public static void main(String[] args) {
        char bubbledA = 'ⓐ';
        int lowerCaseOffset = bubbledA - 'a';
        int upperCaseOffset = bubbledA - 'A';

        String input = "Hello";
        StringBuilder bubbledOutput = new StringBuilder();
        for (Character c : input.toCharArray()) {
            if (Character.isUpperCase(c)) {
                bubbledOutput.append((char)(c + upperCaseOffset));
            } else {
                bubbledOutput.append((char)(c + lowerCaseOffset));
            }
        }

        System.out.println(bubbledOutput.toString());
    }
}

<强>输出

ⓗⓔⓛⓛⓞ

答案 3 :(得分:1)

使用for循环:

for (char i='a';i<'z';i++)
    str = str.replaceAll(i,bubbled[i-'a']);
for (char i='A';i<'Z';i++)
    str = str.replaceAll(i,bubbled[i-'A'+26]);

当然,这不会太有效,因为字符串是不可变的。