连接字符以形成字符串会产生不同的结果

The concatenation of chars to form a string gives different results(连接字符以形成字符串会产生不同的结果)

本文介绍了连接字符以形成字符串会产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why, when I use the operation below to sum chars, does it return numbers instead of chars? Shouldn't it give the same result?

ret += ... ; // returns numbers

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

下面的代码复制了字符:

The code below duplicates the chars:

doubleChar("The") → "THhee"

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); 

是字符串连接的结果.Java 语言规范声明

is the result of String concatenation. The Java language specification states

字符串连接的结果是一个String对象的引用那是两个操作数字符串的连接.那些角色左边的操作数在右边的字符之前新创建的字符串中的操作数.

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); 

是加法运算符应用于两种数字类型的结果.Java 语言规范声明

is the result of the additive operator applied to two numeric types. The Java language specification states

二元 + 运算符在应用于两个操作数时执行加法数字类型,产生操作数的总和.[...]数字操作数上的加法表达式的类型是 promoted其操作数的类型.

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.

becomes an int holding the sum of the two char values. That is then concatenated to ret.

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

You might also want to know this about the compound assignment expression +=

E1 op= E2 形式的复合赋值表达式是等价的到E1 = (T) ((E1) op (E2)),其中TE1的类型,除了E1只评估一次.

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

这篇关于连接字符以形成字符串会产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:连接字符以形成字符串会产生不同的结果

基础教程推荐