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

后端 未结 9 1616
南笙
南笙 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:21
    String s = "xyz";
    for(int i = 0; i < s.length(); i++)
    {
       char c = s.charAt(i);
    }
    

     

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

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

    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);
    }
    
    0 讨论(0)
提交回复
热议问题