在Java中迭代字符串字符的方法有:

使用StringTokenizer ? 将String转换为char[]并对其进行迭代。

最简单/最好/最正确的迭代方法是什么?


当前回答

所以通常有两种方法在java中迭代字符串,这已经被很多人在这个线程中回答了,只是添加了我的版本 首先是使用

String s = sc.next() // assuming scanner class is defined above
for(int i=0; i<s.length(); i++){
     s.charAt(i)   // This being the first way and is a constant time operation will hardly add any overhead
  }

char[] str = new char[10];
str = s.toCharArray() // this is another way of doing so and it takes O(n) amount of time for copying contents from your string class to the character array

如果性能受到威胁,那么我会建议在常数时间内使用第一个,如果不是,那么考虑到java中字符串类的不可变性,那么使用第二个会使您的工作更容易。

其他回答

如果你需要遍历字符串的代码点(见这个答案),一个更短/更可读的方法是使用Java 8中添加的CharSequence#codePoints方法:

for(int c : string.codePoints().toArray()){
    ...
}

或者直接使用流而不是for循环:

string.codePoints().forEach(c -> ...);

如果你想要字符流,还有CharSequence#chars(尽管它是IntStream,因为没有CharStream)。

我使用一个for循环来迭代字符串,并使用charAt()来获取每个字符以检查它。由于String是用数组实现的,charAt()方法是一个常量时间操作。

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

这就是我要做的。对我来说这似乎是最简单的。

至于正确性,我不相信这里存在。这完全取决于你的个人风格。

这里有一些专门的类:

import java.text.*;

final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
   // process c
   ...
}

注意,如果处理BMP (Unicode基本多语言平面)之外的字符,即u0000-uFFFF范围之外的代码点,则此处描述的大多数其他技术都将失效。这种情况很少发生,因为在此之外的代码点大多分配给了死语言。但除此之外还有一些有用的字符,例如一些用于数学符号的代码点,以及一些用于编码中文专有名称的代码点。

在这种情况下,你的代码将是:

String str = "....";
int offset = 0, strLen = str.length();
while (offset < strLen) {
  int curChar = str.codePointAt(offset);
  offset += Character.charCount(curChar);
  // do something with curChar
}

Character.charCount(int)方法需要Java 5+。

来源:http://mindprod.com/jgloss/codepoint.html

两个选项

for(int i = 0, n = s.length() ; i < n ; i++) { 
    char c = s.charAt(i); 
}

or

for(char c : s.toCharArray()) {
    // process c
}

第一种可能更快,第二种可能更易读。