【问题标题】:modify a stringbuilder while iterating on it在迭代字符串生成器时对其进行修改
【发布时间】:2015-08-16 08:45:48
【问题描述】:

在 Java 中,我可以迭代 StringBuilder 的内容并删除/插入/替换字符以使循环保持一致吗?如果是这样,最佳实践,我应该使用 for 循环、迭代器还是从零到 length()-1 的传统循环?例如,

StringBuilder b=new StringBuilder("12345");
for (int i=0; i< b.length(); i++) //traditional loop, iterator(which?),other?
  char c= b.chartAt(i);
  if(c == '1') b.deleteCharAt(i); // reduce the size,what is i pointing to now?
  if(c=='2') b.insert(i,"two"); //increase the size

}

编辑:假设我有一个大字符串,我需要对其进行更改,并且我不想每次都生成副本。 StringBuilder 是一个可变字符串,如何正确使用它来进行就地更改?我知道我可以在字符串本身上使用 replace / replaceall,但这不是重点。

【问题讨论】:

  • 如果你想删除任何东西,最好从字符串的末尾迭代到开头。
  • 你为什么有b.insert(2,"two")?应该是i2?
  • 谢谢,已修复!当然是我!

标签: java string stringbuilder


【解决方案1】:

我认为你可以做到。我同意 STaefi,你应该从头到尾迭代:

StringBuilder b=new StringBuilder("12345");
        for (int i = b.length() - 1; i >=0 ; i--){ //traditional loop, iterator(which?),other?
            char c = b.charAt(i);
            if(c == '1') b.deleteCharAt(i); // reduce the size,what is i pointing to now?
            if(c=='2') b.insert(2,"two"); //increase the size
        }

【讨论】:

    【解决方案2】:

    如果您想遍历 StringBuilder,那么您可能做错了,因为它只是为不同的目的而设计的(例如,您从它的名称中注意到动态字符串建筑物)。如果您想通过更改其中一些来获得新的字符序列,如果您没有特定要求,请使用String

    【讨论】:

    • 重点是,假设我有一个大字符串,我知道我必须做很多更改。我不想一直创建副本,而是使用 StringBuilder 作为可变字符串,这就是这个类的全部内容。
    • 如果你想要可变性,为什么不使用 StringBuffer 呢?为什么必须使用 StringBuilder?我的意思是它可能会让其他开发人员感到困惑......
    • 对不起,我不明白。 StringBuffer 和 StringBuilder 本质上是一样的,只是关心线程安全,据我所知
    【解决方案3】:

    您可以这样做,但您应该相应地更改i 的值。

    StringBuilder b=new StringBuilder("12345");
    for (int i=0; i< b.length(); i++) {
          char c= b.chartAt(i);
          if(c == '1'){
              b.deleteCharAt(i);
              i--; // because you don't want to miss out the next char after deleting the present char
          }
          else if(c=='2'){
                 b.insert(i,"two"); // I am not sure you want 2 or i
                 i=i+2; // change this accordingly.
               }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-03
      • 1970-01-01
      • 2012-03-07
      • 2010-12-14
      • 2022-11-13
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 2018-06-16
      相关资源
      最近更新 更多