首页 > 解决方案 > 如何用 unicode 字符替换字符串

问题描述

我打算用普通字符串替换字符串为分割字符串,但是普通字符串之间的长度差异为 62,分割长度结果为 117,所以当我们写 'a' 按钮时它不会更改为 '' 还有另一种更容易编写替换字符串的方法吗?

public static String doublestruck(String input){
    String normal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String split = "ℂℍℕℙℚℝℤ";

    String output = "";
    char letter;
    for(int i = 0; i < input.length(); i++){
        letter = input.charAt(i);
        int a = normal.indexOf(letter);
        output += (a != -1) ? split.charAt(a):letter;
    }
    return new StringBuilder(output).toString();
}

标签: java

解决方案


(U+1D7DC) 之类的字母不在基本多语言窗格中,因此在 Java 中占用两个char值。

而不是charAt您需要使用codePointAt并找到您需要使用的正确偏移量,offsetByCodePoint而不是直接使用相同的索引。所以split.charAt(a)需要换成split.codePointAt(spli.offsetByCodePoint(0, a))


推荐阅读