Java减去字符串中char码的值

Java subtract value of char code in string

我正在尝试将字符串转换为希伯来语编码 (windows 1255),因此我需要从任何字符 1264 的值中减去并放入新字符串中。

这是我要转换的 javascript 中的代码:

strText = strText.replace(/[א-ת]/ig, function(a,b,c) {
        return escape(String.fromCharCode(a.charCodeAt(0)-1264));
    });

这是我在 Java 中所做的,但我没有得到预期的值:

String test = "שלום";
byte[] testBytes = test.getBytes();
String testResult = "";
for (int i = 0;i < testBytes.length;i++)
     {
        testResult += (char)((int)testBytes[i]-1264);
     }

我做错了什么?

因为你使用的是byte数组,最大可以存储255个,最小0个,所以它只能存储扩展的ASCII字符(afaik它不包括希伯来字符).您需要的是一个 char 数组(可以存储任何 unicode 字符)。

所以,改变这个

byte[] testBytes = test.getBytes();

至此

char[] testBytes = test.toCharArray();

调用时需要传递编码String.getBytes(String)。像

public static void main(String[] args) {
    String test = "שלום";
    try {
        byte[] testBytes = test.getBytes("UTF-8");
        String testResult = new String(testBytes, "UTF-8");
        System.out.println(testResult);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

输出是

שלום