java - 连接字符以形成字符串会给出不同的结果

标签 java string char concatenation

为什么,当我使用下面的操作对字符求和时,它返回的是数字而不是字符?它不应该给出相同的结果吗?

ret += ... ; // returns numbers

ret = ret + ...; // returns chars

下面的代码复制了字符:

doubleChar("The") → "TThhee"

public String doubleChar(String str) {

    String ret = "";
    for(int i = 0; i < str.length(); i++) {
        ret = ret + str.charAt(i) + str.charAt(i); // it concatenates the letters correctly
        //ret += str.charAt(i) + str.charAt(i); // it concatenates numbers
    }
    return ret;
}

最佳答案

下面表达式的结果

ret + str.charAt(i) + str.charAt(i); 

是字符串拼接的结果。 The Java language specification states

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

结果

str.charAt(i) + str.charAt(i); 

是应用于两种数值类型的加法运算符的结果。 The Java language specification states

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. [...] The type of an additive expression on numeric operands is the promoted type of its operands.

在这种情况下

str.charAt(i) + str.charAt(i); 

变成一个 int 保存两个 char 值的总和。然后将其连接到 ret


您可能还想了解复合赋值表达式 +=

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

换句话说

ret += str.charAt(i) + str.charAt(i);

相当于

ret = (String) ((ret) + (str.charAt(i) + str.charAt(i)));
                      |                ^ integer addition
                      |
                      ^ string concatenation

关于java - 连接字符以形成字符串会给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387948/

相关文章:

java - 尝试最长前缀匹配

c++ - 成功打印超出范围的字符串索引

c++ - std::string 声明的函数不会提示返回 char *

regex - 在 Perl 中打印没有子字符串的字符串

c# - 如何将单个字符转换为字符串?

java - ColdFusion 邮件假脱机超时

java - charAt 方法返回一个整数。需要转成int

java - java生成唯一id(不超过64位)

c++ - 如何将字符串 vector 传递给 foo(char const *const *const)?

haskell - 我似乎无法在 haskell 中设置字符的值?