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

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

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


当前回答

在Java 8中,我们可以将其求解为:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
str.codePoints().forEachOrdered(i -> System.out.print((char)i));

方法chars()返回doc中提到的IntStream:

返回一个int 0的流,从this扩展char值 序列。将传递映射到代理代码点的任何字符 通过粗略的。如果序列发生突变,而流发生突变 被读取时,结果是未定义的。

方法codePoints()也会根据文档返回一个IntStream:

返回此序列中的代码点值流。任何 序列中遇到的代理项对被组合,就像由 的性格。toCodePoint并将结果传递给流。任何 其他代码单位,包括未配对的普通BMP字符 代理和未定义的代码单元从0扩展到int值 然后传递给流。

字符和码点有什么不同?如本文所述:

Unicode 3.1 added supplementary characters, bringing the total number of characters to more than the 2^16 = 65536 characters that can be distinguished by a single 16-bit char. Therefore, a char value no longer has a one-to-one mapping to the fundamental semantic unit in Unicode. JDK 5 was updated to support the larger set of character values. Instead of changing the definition of the char type, some of the new supplementary characters are represented by a surrogate pair of two char values. To reduce naming confusion, a code point will be used to refer to the number that represents a particular Unicode character, including supplementary ones.

最后,为什么forEachOrdered而不是forEach ?

forEach的行为是显式的不确定的,其中forEachOrdered为流的每个元素执行一个操作,如果流具有定义的遇到顺序,则按照流的遇到顺序执行。因此forEach并不保证顺序会被保持。请检查这个问题以了解更多信息。

关于字符、码位、字形和字素之间的区别,请检查这个问题。

其他回答

StringTokenizer完全不适合将字符串分解为单个字符的任务。使用String#split(),你可以通过使用一个不匹配的正则表达式轻松做到这一点,例如:

String[] theChars = str.split("|");

但是StringTokenizer不使用正则表达式,并且没有可以指定的分隔符字符串来匹配字符之间的空白。你可以使用一个可爱的小技巧来完成同样的事情:使用字符串本身作为分隔符字符串(使其中的每个字符都成为分隔符),并让它返回分隔符:

StringTokenizer st = new StringTokenizer(str, str, true);

但是,我只是为了排除它们而提到这些选项。这两种技术都将原始字符串分解为单字符字符串,而不是char原语,并且都以对象创建和字符串操作的形式涉及大量开销。与在for循环中调用charAt()相比,后者几乎没有开销。

public class Main {

public static void main(String[] args) {
     String myStr = "Hello";
     String myStr2 = "World";
      
     for (int i = 0; i < myStr.length(); i++) {    
            char result = myStr.charAt(i);
                 System.out.println(result);
     } 
        
     for (int i = 0; i < myStr2.length(); i++) {    
            char result = myStr2.charAt(i);
                 System.out.print(result);              
     }    
   }
}

输出:

H
e
l
l
o
World

如果需要性能,那么必须在环境中进行测试。没有别的办法。

下面是示例代码:

int tmp = 0;
String s = new String(new byte[64*1024]);
{
    long st = System.nanoTime();
    for(int i = 0, n = s.length(); i < n; i++) {
        tmp += s.charAt(i);
    }
    st = System.nanoTime() - st;
    System.out.println("1 " + st);
}

{
    long st = System.nanoTime();
    char[] ch = s.toCharArray();
    for(int i = 0, n = ch.length; i < n; i++) {
        tmp += ch[i];
    }
    st = System.nanoTime() - st;
    System.out.println("2 " + st);
}
{
    long st = System.nanoTime();
    for(char c : s.toCharArray()) {
        tmp += c;
    }
    st = System.nanoTime() - st;
    System.out.println("3 " + st);
}
System.out.println("" + tmp);

在Java网上,我得到:

1 10349420
2 526130
3 484200
0

在Android x86 API 17上,我得到:

1 9122107
2 13486911
3 12700778
0

这里有一些专门的类:

import java.text.*;

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

所以通常有两种方法在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中字符串类的不可变性,那么使用第二个会使您的工作更容易。