将 Java 中的字符串中的多个 char 转换为 int

Convert more than one char to an int in a string in Java

我知道如何将单个 char 转换为 int,但如何将 String 转换为 char,这样我就可以将 chars 到 ints?例如,对于字符串 hello:

chars[1] = h => 104
chars[2] = e => 101
chars[3] = l => 108
chars[4] = l => 108
chars[5] = o => 111

输出应该可以很容易地将五个字母的 Strings 转换为五个单独的整数,每个整数代表一个字符,然后将它们转换回 char 并将它们打印为单个 String 再次.

你可以这样试试:

String s = "hello";
char[] data = s.toCharArray(); // returns a length 5 char array ( 'h','e','l','l','o' )

现在可以调用这个函数把它转成int了

int charToInt(char []data,int start,int end) throws NumberFormatException
{
    int result = 0;
    for (int i = start; i < end; i++)
    {
        int digit = (int)data[i] - (int)'0';
        if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
        result *= 10;
        result += digit;
    }
    return result;
}

可以在StringBuilderclass的构造函数参数中传递给定的字符串,使用codePointAt(int)方法。它 returns 指定索引处字符的 ASCII 值。

StringBuilder 中还有其他有用的方法,例如 codePointBefore(int) and appendCodePoint(int),它允许您查看字符之前的代码点并将具有指定代码点的字符附加到 StringBuilder , 分别.

使用getBytes(),你可以得到一个byte[],其中包含String中每个字母的数字表示:

byte[] text = "hello".getBytes();

for(byte b : text) {
    System.out.println(b);
}

这给出了与以下相同的结果:

String text = "hello";

for(char c : text.toCharArray()) {
    System.out.println((int) c);
}

这是我能想到的实现此目标的最简单方法。要将其转换回字符串:

byte[] byteArray = "hello".getBytes();

String string = new String(byteArray);

我在这里假设每个 charint 值应该对应于 Unicode code point of that character. If so, then the solution is trivial: you only need to type-cast between the char and int types. This is because in Java, a char is actually an Integral type,就像 int 一样。 char 类型可以包含表示 16 位 Unicode 字符代码点的整数值('\u0000''\uffff'0...65535)。

解决方案是首先使用 toCharArrayString 转换为 char[]。然后,只需将每个 char 转换为 int 即可获得 Unicode 代码点值:

int capitalACodePoint = (int)'A';

类似地,转换为 char 以取回值:

char capitalA = (char) 65;

一个可运行的例子:

String input =  "hello";        
List<Integer> codePoints = new ArrayList<>();

for (char c : input.toCharArray()) {
    int codePoint = (int)c;
    codePoints.add(codePoint);
    System.out.println(String.format(
            "char$ %d %s equals %d", 
            codePoints.size(), c, codePoint));
}

StringBuilder sb = new StringBuilder();

for (int codePoint : codePoints) {
    sb.append((char) codePoint);
}
System.out.println(sb);

打印出来

char$ 1 h equals 104
char$ 2 e equals 101
char$ 3 l equals 108
char$ 4 l equals 108
char$ 5 o equals 111
hello

此代码也适用于非 ASCII 字符。将输入更改为

String input =  "©†¿™";

打印出来

char$ 1 © equals 169
char$ 2 † equals 8224
char$ 3 ¿ equals 191
char$ 4 ™ equals 8482
©†¿™