string.concat 和 + 运算符在字符串连接中的区别
Difference between string.concat and the + operator in string concatenation
(这个问题可能是重复的,但我真的不明白其他答案)
您有以下代码:
String str ="football";
str.concat(" game");
System.out.println(str); // it prints football
但使用此代码:
String str ="football";
str = str + " game";
System.out.println(str); // it prints football game
那么有什么区别,到底发生了什么?
str.concat(" game");
与str + " game";
同义。如果您不将结果分配回某个地方,它就会丢失。你需要做的:
str = str.concat(" game");
'concat'函数是不可变的,所以它的结果必须放在一个变量中。使用:
str = str.concat(" game");
(这个问题可能是重复的,但我真的不明白其他答案)
您有以下代码:
String str ="football";
str.concat(" game");
System.out.println(str); // it prints football
但使用此代码:
String str ="football";
str = str + " game";
System.out.println(str); // it prints football game
那么有什么区别,到底发生了什么?
str.concat(" game");
与str + " game";
同义。如果您不将结果分配回某个地方,它就会丢失。你需要做的:
str = str.concat(" game");
'concat'函数是不可变的,所以它的结果必须放在一个变量中。使用:
str = str.concat(" game");