pub*_*oid 2 java string concat add char
所以我想在字符串中添加一个字符,并且在某些情况下想要将这些字符加倍,然后将其添加到字符串中(即首先添加到字符串中).我尝试了这个,如下所示.
char s = 'X';
String string = s + s;
Run Code Online (Sandbox Code Playgroud)
这引发了一个错误,但我已经在字符串中添加了一个字符,所以我尝试了:
String string = "" + s + s;
Run Code Online (Sandbox Code Playgroud)
哪个有效.为什么在求和中包含一个字符串会导致它起作用?是否添加了一个字符串属性,由于存在字符串,它们只能在字符转换为字符串时使用?
这是因为String + Char = String,类似于int + double = double.
尽管其他答案告诉你,Char + Char仍然是int.
字符串s = 1; //由于类型不匹配导致的编译错误.
你的工作代码是(String + Char)+ Char.如果你这样做了:String +(Char + Char)你会在你的字符串中得到一个数字.例:
System.out.println("" + ('x' + 'x')); // prints 240
System.out.println(("" + 'x') + 'x'); // prints xx - this is the same as leaving out the ( ).
Run Code Online (Sandbox Code Playgroud)