【问题标题】:Iterating over String迭代字符串
【发布时间】:2014-04-21 12:30:13
【问题描述】:

我必须遍历字符串的元素,并在每次迭代中执行一些检查。

我的问题是:

哪个更好用:StringStringBuilder

String.charAt(i)StringBuilder.charAt(i)?的运行时间有区别吗

我确实必须修改字符串,我只需要遍历所有元素。

【问题讨论】:

    标签: java string indexing


    【解决方案1】:

    使用 StringBuilder 的唯一原因是为了修改(因为字符串是不可变的)。在这种情况下,您应该对 String 本身进行迭代。

    【讨论】:

      【解决方案2】:

      StringBuilder 在你修改字符串时很有用,String 在你不修改时很有用。

      对于你的情况String

      关于性能:两者都是constant time,或者可以忽略不计[1]

      注意:

      当您修改定义为字符串的字符串时,它会创建新字符串而不是实际修改它,这就是为什么最好使用StringBuilder

      例如)

      string a = "hello";
      a = "hai";
      

      这里还创建了一个新的 world 字符串以及已经在字符串池中创建的 hello

      附加:http://blog.vogella.com/2009/07/19/java-string-performanc/

      【讨论】:

        【解决方案3】:

        正如其他人已经说过的,两者之间没有性能差异。您可以通过查看源代码来说服自己。正如您在下面看到的,两者几乎相同。

        String.charAt()

        public char More ...charAt(int index) {
            if ((index < 0) || (index >= count)) {
               throw new StringIndexOutOfBoundsException(index);
            }
            return value[index + offset];
        }
        

        StrringBuilder.charAt()

        public char charAt(int index) {
            if ((index < 0) || (index >= count))
                throw new StringIndexOutOfBoundsException(index);
            return value[index];
        }
        

        换句话说,使用你已有的任何东西。如果您有 String,请使用 String,如果您有 StringBuilder,请使用 StringBuilder。从一个对象转换到另一个对象的成本将大大超过这两种方法之间的任何性能差异。

        【讨论】:

          【解决方案4】:
          • StringStringBuilder 都是 Java 中的类。
          • String 用于创建字符串常量。
          • StringBuilder 名称本身表示要构建字符串。这意味着我们可以轻松做到
            使用此类进行修改。

          在您的情况下,您可以简单地使用 String 类。

          字符串在 Java 中是不可变的。这意味着每次修改后,都会使用最新修改的值创建一个新的String

          String str = new String("AVINASH");
          char check = 's';
          int length=str.length();
          for(int i=0; i <length ; i++) {
             if (check==str.charAt(i)) {
                 System.out.println("Matched");
             }
          }
          

          【讨论】:

            猜你喜欢
            • 2012-10-23
            • 2011-06-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-20
            • 2011-07-22
            • 2013-02-20
            相关资源
            最近更新 更多