为什么我可以在字符串中添加字符,但不能在字符中添加字符? [英] Why can I add characters to strings but not characters to characters?
问题描述
因此,我想在字符串中添加一个字符,在某些情况下,我想将该字符加倍,然后将其添加到字符串中(即首先添加到其自身中)。我尝试了如下操作。
So I wanted to add a character to a string, and in some cases wanted to double that characters then add it to a string (i.e. add to it itself first). I tried this as shown below.
char s = 'X';
String string = s + s;
这引发了错误,但是我已经在字符串中添加了单个字符,所以我尝试了:
This threw up an error, but I'd already added a single character to a string so I tried:
String string = "" + s + s;
曾工作过。为什么在求和中包含字符串会导致它起作用?是否要添加字符串属性,该字符串属性由于存在字符串而只能在字符转换为字符串时使用?
Which worked. Why does the inclusion of a string in the summation cause it to work? Is adding a string property which can only be used by characters when they're converted to strings due to the presence of a string?
推荐答案
这是因为String + Char = String,类似于int + double = double的方式。
It's because String + Char = String, similar to how an int + double = double.
Char + Char的数据是int的,尽管其他答案告诉您。
Char + Char is int despite what the other answers tell you.
字符串s = 1; //由于类型不匹配而导致的编译错误。
String s = 1; // compilation error due to mismatched types.
您的工作代码为(String + Char)+ Char。如果您这样做:String +(Char + Char),您将在字符串中得到一个数字。示例:
Your working code is (String+Char)+Char. If you had done this: String+(Char+Char) you would get a number in your string. Example:
System.out.println("" + ('x' + 'x')); // prints 240
System.out.println(("" + 'x') + 'x'); // prints xx - this is the same as leaving out the ( ).
这篇关于为什么我可以在字符串中添加字符,但不能在字符中添加字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!