【问题标题】:Help in debugging the string concatenation code帮助调试字符串连接代码
【发布时间】:2010-04-16 10:50:28
【问题描述】:

我有一个连接字符串的代码。但是,由于某种原因,最终字符串不是所需字符串的组合。考虑以下代码:

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

第一个 sout 语句正确显示了 cusEmail[i] 中的字符串。但是,一旦连接,第二个 sout 将显示空白/空。这有什么原因吗?我是否正确连接它?

【问题讨论】:

    标签: java debugging concatenation


    【解决方案1】:

    字符串是 不可变的 。这意味着toList.concat(..) 不会更改toList。相反,它返回一个新字符串:

     toList = toList.concat(..);
    

    不过,最好使用StringBuilder.append(..)

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

    更好的(就代码重用而言)方法是使用实​​用程序来使用分隔符连接字符串。喜欢ArrayUtils.join(emailsArray, "; ");(来自commons-lang)

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        • 1970-01-01
        相关资源
        最近更新 更多