【问题标题】:Difference between string.concat and the + operator in string concatenation [duplicate]字符串连接中 string.concat 和 + 运算符之间的区别[重复]
【发布时间】:2018-11-10 14:59:25
【问题描述】:

(这个问题可能是重复的,但我真的不明白其他答案)

你有以下代码:

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 仍然具有其原始值。
  • 字符串是不可变的,所以你必须将str.concat(" game"); 赋值给一个变量

标签: java string-concatenation


【解决方案1】:

str.concat(" game");str + " game"; 含义相同。如果您不将结果分配回某处,它就会丢失。你需要做的:

str = str.concat(" game");

【讨论】:

  • 那么到底发生了什么事情呢? : str.concat(" game") 创建了一个新的字符串对象 "football game" 但它并没有改变 str 引用,str 仍然引用 "football"
  • @BaselQarabash 是的
【解决方案2】:

'concat' 函数是不可变的,所以它的结果必须放在一个变量中。使用:

str = str.concat(" game");

【讨论】:

  • 只是一件小事:Strings 是不可变的,而不是 concat 函数
猜你喜欢
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 2014-06-12
相关资源
最近更新 更多