繁体   English   中英

字符串连接不起作用,还是一个错误

[英]String concatenation not working, or is it a bug

我已经编写了一些代码,并使用了我用+ =组合而成的字符串(因为我只做过几次。

稍后,我使用了另一个字符串并使用了concat()函数。 串联不起作用。

所以我在Junit中写了一个小方法(带有Eclipse)...

@Test
public void StingConcatTest(){

    String str = "";

    str += "hello ";
    str += " and goodbye";

    String conc="";
    conc.concat("hello ");
    conc.concat(" and goodbye");
    System.out.println("str is: " + str + "\nconc is: "+ conc);

输出是...

str is: hello  and goodbye
conc is: 

因此,要么我发疯,正在做错事(很可能是),JUNIT中有问题,或者我的JRE / eclipse有问题。

请注意,stringbuilder运行正常。

大卫。

好的,我们每天至少看到几次这个问题。

Stringsimmutable ,因此对String的所有操作都会产生新的String

conc= conc.concat("hello "); 您需要重新将结果重新分配给字符串

您必须尝试:

String conc="";
conc = conc.concat("hello ");
conc = conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);

为了优化,您可以编写:

String conc="";
conc = conc.concat("hello ").concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);

如果计划串联多个字符串,则还可以使用StringBuilder:

StringBuilder builder = new StringBuilder();
builder.append("hello");
builder.append(" blabla");
builder.append(" and goodbye");
System.out.println(builder.toString());

concat()返回串联的字符串。

public static void main(String [] args) {
    String s = "foo";

    String x = s.concat("bar");

    System.out.println(x);
}

concat返回一个字符串。 它不会更新原始的String。

String.concat不会更改其调用的字符串-它返回一个新字符串,该字符串是该字符串和参数串联在一起的。

顺便说一句:使用concat或+ =的字符串连接不是很有效。 您应该改用StringBuilder类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM