在 Java 中将字符串数组中的选择性元素转换为它们的 ascii 值



我目前正在做一个项目,我有一个 String 数组,其中包含 8 个值,这些值的数量但存储为字符串。字符串[3]和字符串[7]是存储为字符串的字母,我需要将其转换为其ASCII值,但我似乎无法在java中做到这一点。我不断收到一个错误,说我无法将字符串类型转换为 int 类型,并且我不知道任何其他方法可以将这些字符串字母转换为其 ASCII 值。这是我到目前为止的代码...

String stringInfo [] = input.split(",");
    int info [] = new int [8];
    int x = 0;
    while (x<stringInfo.length) {
        info[x] = Integer.parseInt(stringInfo[x]);
        System.out.println(info[x]);
        x++;
    }

所以在该数组中,这两个值需要转换为 ASCII,但该代码不断出现错误,我不知道如何解决它。我该怎么做?

执行此操作的最佳方法是首先将字符串转换为字符,然后将字符转换为 int。我知道这听起来很多,但它实际上只是一行代码。

int ascii = (int) mystring.charAt(0);

这样做的原因是字符(char(是Java中的主要类型,它们本质上只是位,这就是为什么您实际上可以使用==而不是.equals来比较char

彼此的原因。

这是一个使用 ascii 代码将无符号数字字符串转换为整数的函数:

static int stringToNumber(String input) {
    int output = 0;
    for (int x = 0; x < input.length(); x++) {
        output = output * 10 + (input.charAt(x) - '0');
    }
    return output;
}

和你的代码

String stringInfo [] = input.split(",");
    int info [] = new int [8];
    int x = 0;
    while (x<stringInfo.length) {
        info[x] = stringToNumber(stringInfo[x]);
        System.out.println(info[x]);
        x++;
}

但是如果你不需要 ascii 代码或者你的号码是有符号的号码 java 使它更容易,你只能使用此方法将字符串转换为数字

Integer result = Integer.valueOf(stringInfo[x]);

和你的代码:

String stringInfo [] = input.split(",");
    int info [] = new int [8];
    int x = 0;
    while (x<stringInfo.length) {
        info[x] = Integer.valueOf(stringInfo[x]);
        System.out.println(info[x]);
        x++;
}

你可以试试-

String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
    while (x<stringInfo.length) {
        info[x] = stringInfo.charAt(x);
        System.out.println(info[x]);
        x++;
    }

stringInfo.charAt(i)将在stringInfo index(i)时给出 Ascii 值

最新更新