1

当我只想根据标准将特定字符转换为十六进制时,我的 java 代码由于我无法弄清楚将字符串转换为十六进制的原因。请参阅下面的代码和输出。

for (int n = 0; n < line.length(); ++n) {
    char aChar = line.charAt(n);
    if (Character.isLetter(aChar) || Character.isDigit(aChar)
            || aChar == '_' || aChar == '-' || aChar == '.'
            || aChar == '*') {
        encoded += +aChar;
    } else if (aChar == ' ') {
        encoded += +'+';
    } else {
        String hexValue = Integer.toHexString(aChar);
        encoded += '%' + hexValue;
    }
}

System.out.println("The encoded string is: " + encoded);

System.out.println("Length in chars is: " + encoded.length());

输出:

输入一行要进行 URL 编码的文本

aaddcc

读取的字符串是:aaddcc

字符长度为:6

编码后的字符串为:97971001009999

字符长度为:14

上面的代码是它的肉

4

1 回答 1

0

如评论中所述,失败的原因是您尝试进行字符串连接的方式存在一个小错误。连接两个String对象的正确方法如下例所示:

"Hello " + "World"; //Adding two String constants
"1st String" + stringVariable; //Appending a String variable to a String constant
firstString + secondString; //Concatenating two String variables
"Favourite letter: " + 'a'; //Join a String and a char
"Age: " + 21; //Join a String and an int - result is "Age: 21"

+=您正在使用的是一个快捷方式,但本质x += y上扩展为x = x + y. 你写encoded += + '+'这个的地方扩展到encoded = encoded + + '+'. char这对于-type 变量没有意义,但是如果将char转换为int,则编译器可以将表达式解释为encoded + (+43),其中 43 是将'+'字符转换为int(即(int)'+')的结果,并且(+43)是一种不必要的精确方式说这43是积极的。

以下两行是等价的

encoded += +'+';
encoded += 43;

同样,当您使用 时aChar,尽管转换为 anint将导致根据当前字符添加不同的整数。

于 2014-03-15T10:18:17.780 回答