开发者

Help in debugging the string concatenation code

开发者 https://www.devze.com 2022-12-27 07:16 出处:网络
I have a code to concatenate strings. However, for some reason, the final string is not a combination of the required strings. Consider the following code :

I have a code to concatenate strings. However, for some reason, the final string is not a combination of the required strings. Consider the following code :

//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);

The first sout statement displays the strings in cusEmail[i] correctly. However, once concatenated, the second sout displays a blank / empty. Any reason for this? Am i concatenating it correctly?


String is immutable . This means that toList.concat(..) doesn't change toList. Instead it returns a new String:

 toList = toList.concat(..);

However, it is more advisable to use StringBuilder.append(..):

StringBuilder toList = new StringBuilder();
for (...) {
    sb.append(emails[i]);
    sb.append("; ");
}
...
return sb.toString();

An even better (in terms of code reuse) way is to use an utility for contatenating strings with delimiters. Like ArrayUtils.join(emailsArray, "; "); (from commons-lang)


String objects are immutable. Calling concat on toList will not change the value of the toList object. Instead concat will return a different String object that is a concatenation of the two strings. For your example, you will want to store the result of each of the calls to concat in the toList variable.

For example,

toList = toList.concat(cusEmail[i]);

An alternative to using the concat method would be to use the concatenation operator. This might be a little nicer to read.

toList = toList + cusEmail[i];

Note, however, that each time one string is concatenated onto another string, a new String object needs to be created that contains copies of the information in the two original strings. This can be a costly way of building a string when it is done over and over in a loop such as what you have. This is true whether you use the concat method or the concatenation operator. An alternative is to use a StringBuilder object to build your string.

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());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号