gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:52:02 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com