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

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

So I thought:

for (char c : "xyz")

but I get a compiler error:

MyClass.java:20: foreach not applicable to expression type

How can I do this?

This question is related to java string loops foreach char

The answer is


String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}

 


You need to convert the String object into an array of char using the toCharArray() method of the String class:

String str = "xyz";
char arr[] = str.toCharArray(); // convert the String object to array of char

// iterate over the array using the for-each loop.       
for(char c: arr){
    System.out.println(c);
}

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.


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.


You can also use a lambda in this case.

    String s = "xyz";
    IntStream.range(0, s.length()).forEach(i -> {
        char c = s.charAt(i);
    });

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

for (String s : "xyz".split("")) {
    System.out.println(s);
}

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.


Unfortunately Java does not make String implement Iterable<Character>. This could easily be done. There is StringCharacterIterator but that doesn't even implement Iterator... So make your own:

public class CharSequenceCharacterIterable implements Iterable<Character> {
    private CharSequence cs;

    public CharSequenceCharacterIterable(CharSequence cs) {
        this.cs = cs;
    }

    @Override
    public Iterator<Character> iterator() {
        return new Iterator<Character>() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < cs.length();
            }

            @Override
            public Character next() {
                return cs.charAt(index++);
            }
        };
    }
}

Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))...


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?

Examples related to char

How can I convert a char to int in Java? C# - How to convert string to char? How to take character input in java Char Comparison in C Convert Char to String in C cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to get the real and total length of char * (char array)? Why is conversion from string constant to 'char*' valid in C but invalid in C++ char *array and char array[] C++ - How to append a char to char*?