Java 调试字符串串联代码的帮助
我有一个连接字符串的代码。但是,由于某些原因,最终字符串不是所需字符串的组合。考虑下面的代码:Java 调试字符串串联代码的帮助,java,debugging,concatenation,Java,Debugging,Concatenation,我有一个连接字符串的代码。但是,由于某些原因,最终字符串不是所需字符串的组合。考虑下面的代码: //cusEmail is of type String[] String toList = ""; for(i=0; i < cusEmail.length - 1; i++) { toList.concat(cusEmail[i]); toList.concat("; "); System.out.println(cusEmail[i]); } toList.conc
//cusEmail is of type String[]
String toList = "";
for(i=0; i < cusEmail.length - 1; i++) {
toList.concat(cusEmail[i]);
toList.concat("; ");
System.out.println(cusEmail[i]);
}
toList.concat(cusEmail[i]);
System.out.println(toList);
//cusEmail的类型为String[]
字符串toList=“”;
对于(i=0;i
第一个sout语句正确显示cusEmail[i]中的字符串。但是,一旦连接,第二个sout将显示空白/空。有什么原因吗?我是否正确地连接了它?
String
对象是不可变的。在toList
上调用concat
不会更改toList
对象的值。相反,concat
将返回一个不同的String
对象,该对象是两个字符串的串联。例如,您需要将对concat
的每次调用的结果存储在toList
变量中
比如说,
toList = toList.concat(cusEmail[i]);
使用concat
方法的替代方法是使用串联运算符。这本书读起来可能会好一点
toList = toList + cusEmail[i];
但是,请注意,每次将一个字符串连接到另一个字符串时,都需要创建一个新的string
对象,其中包含两个原始字符串中信息的副本。当在循环中一遍又一遍地构建字符串时,这可能是一种代价高昂的构建字符串的方法。无论您使用的是concat
方法还是串联运算符,都是如此。另一种方法是使用StringBuilder
对象构建字符串
StringBuilder toList = new StringBuilder();
for(i=0; i < cusEmail.length - 1; i++) {
toList.append(cusEmail[i]);
toList.append("; ");
System.out.println(cusEmail[i]);
}
toList.append(cusEmail[i]);
System.out.println(toList.toString());
StringBuilder toList=new StringBuilder();
对于(i=0;i
字符串是不可变的。这意味着toList.concat(..)
不会更改toList
。而是返回一个新字符串:
toList = toList.concat(..);
但是,更可取的做法是使用StringBuilder.append(..)
:
一种更好的方法(就代码重用而言)是使用一个实用程序来用分隔符连接字符串。Like(来自commons lang)
StringBuilder toList = new StringBuilder();
for (...) {
sb.append(emails[i]);
sb.append("; ");
}
...
return sb.toString();