在 Java 中迭代 StringBuilder 的标准方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24742341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Standard way to iterate over a StringBuilder in Java?
提问by jmite
I was quite surprised that I couldn't find an existing questions answering this.
我很惊讶我找不到回答这个问题的现有问题。
What is the standard way to iterate over all characters in a StringBuilder in Java?
在 Java 中迭代 StringBuilder 中所有字符的标准方法是什么?
The obvious route is to just convert it to a String then use toCharArray(). The problem is, I'm dealing with thousands of unique strings, with which I do a lot of appending, and I think I'm getting memory and performance issues from having to intern them all.
显而易见的方法是将其转换为字符串,然后使用 toCharArray()。问题是,我正在处理数以千计的唯一字符串,我对这些字符串进行了很多附加操作,而且我认为我不得不将它们全部实习,从而导致内存和性能问题。
EDIT: to clarify, I'm not manually interning Strings, but my understanding was that they were automatically interned, and that if I called toString
for a StringBuilder that they would be interned. Perhaps I have misunderstood.
编辑:澄清一下,我不是手动实习字符串,但我的理解是它们是自动实习的,如果我调用toString
StringBuilder,它们将被实习。可能我理解错了。
采纳答案by chrylis -cautiouslyoptimistic-
First off, if you're interning lots of strings, you're doing something very wrong.
首先,如果你要实习很多字符串,那你就做错了。
More generally, StringBuilder
implements CharSequence
, just like String
. Use an ordinary counter-based for
loop and charAt()
.
更一般地说,StringBuilder
实现CharSequence
,就像String
. 使用普通的基于计数器的for
循环和charAt()
.