How does the concatenation of a String with characters work in Java?
以下是CodingBat的一个问题。
Given a string, return a string where for every char in the original, there are two chars.
e.g.:
1
2
3 doubleChar("The") →"TThhee"
doubleChar("AAbb") →"AAAAbbbb"
doubleChar("Hi-There") →"HHii--TThheerree"
我有两个语句可以做到这一点,但是注释中的语句没有给出异常的输出:
1 2 3 4 5 6 7 8 9 |
如果我将注释部分更改为
您可以通过以下几种方法来解决此问题:
1 |
或
1 | str1 +="" + str.charAt(i) + str.charAt(i); |
或者,正如您已经发现的,可能是最易读的:
1 | str1 = str1 + str.charAt(i) + str.charAt(i); |
方法
1 | str1 += str.charAt(i) + str.charAt(i); |
在两个
根据Java规范:
15.18. Additive Operators
The operators + and - are called the additive operators.
1
2
3
4 AdditiveExpression:
MultiplicativeExpression
AdditiveExpression + MultiplicativeExpression
AdditiveExpression - MultiplicativeExpressionThe additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
If the type of either operand of a + operator is
String , then the operation is string concatenation.Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
In every case, the type of each of the operands of the binary - operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
所以char
每个
Java规范的第157.3节说:
15.15.3. Unary Plus Operator +
The type of the operand expression of the unary + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.
At run time, the value of the unary plus expression is the promoted value of the operand.
因此,添加两个
要解决此问题,可以使用此问题的任何答案:如何将字符转换为字符串?,例如
1 |
或
1 | str1 +="" + str.charAt(i) + str.charAt(i); |
1 2 3 4 5 6 7 8 | public String doubleChar(String str) { String newStr=""; // created variable to store our result. for(int i=0;i<str.length();i++){ // loop through each char in the string. char add = str.charAt(i); // take out single char from the string and store it into am variable. newStr+=""+add+add; // add each character } return newStr; } |
1 2 3 4 5 6 7 8 |
问题是您试图添加两个字符,这与添加两个字符串的行为不同。您所需要做的就是将这个字符保存为一个字符串,然后您可以按照自己的需要添加它们。
1 2 3 4 5 6 7 8 9 |