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

后端 未结 9 1598
南笙
南笙 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:02

    Another useful solution, you can work with this string as array of String

    for (String s : "xyz".split("")) {
        System.out.println(s);
    }
    
    0 讨论(0)
  • 2020-11-30 18:04

    If you use Java 8, you can use chars() on a String to get a Stream of characters, but you will need to cast the int back to a char as chars() returns an IntStream.

    "xyz".chars().forEach(i -> System.out.print((char)i));
    

    If you use Java 8 with Eclipse Collections, you can use the CharAdapter class forEach method with a lambda or method reference to iterate over all of the characters in a String.

    Strings.asChars("xyz").forEach(c -> System.out.print(c));
    

    This particular example could also use a method reference.

    Strings.asChars("xyz").forEach(System.out::print)
    

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 18:09

    You can also use a lambda in this case.

        String s = "xyz";
        IntStream.range(0, s.length()).forEach(i -> {
            char c = s.charAt(i);
        });
    
    0 讨论(0)
  • 2020-11-30 18:10

    The easiest way to for-each every char in a String is to use toCharArray():

    for (char ch: "xyz".toCharArray()) {
    }
    

    This gives you the conciseness of for-each construct, but unfortunately String (which is immutable) must perform a defensive copy to generate the char[] (which is mutable), so there is some cost penalty.

    From the documentation:

    [toCharArray() returns] a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

    There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator, etc) but if you're willing to pay the cost toCharArray() for-each is the most concise.

    0 讨论(0)
  • 2020-11-30 18:18

    For Travers an String you can also use charAt() with the string.

    like :

    String str = "xyz"; // given String
    char st = str.charAt(0); // for example we take 0 index element 
    System.out.println(st); // print the char at 0 index 
    

    charAt() is method of string handling in java which help to Travers the string for specific character.

    0 讨论(0)
提交回复
热议问题