How do I apply the for-each loop to every character in a String?

后端 未结 9 1764
南笙
南笙 2020-11-30 17:32

So I want to iterate for each character in a string.

So I thought:

for (char c : \"xyz\")

but I get a compiler error:



        
9条回答
  •  甜味超标
    2020-11-30 18:06

    In Java 8 we can solve it as:

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

    The method chars() returns an IntStream as mentioned in doc:

    Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

    Why use forEachOrdered and not forEach ?

    The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

    We could also use codePoints() to print, see this answer for more details.

提交回复
热议问题