What is the easiest/best/most correct way to iterate through the characters of a string in Java?

前端 未结 15 1423
挽巷
挽巷 2020-11-22 11:14

StringTokenizer? Convert the String to a char[] and iterate over that? Something else?

15条回答
  •  日久生厌
    2020-11-22 11:36

    If you need to iterate through the code points of a String (see this answer) a shorter / more readable way is to use the CharSequence#codePoints method added in Java 8:

    for(int c : string.codePoints().toArray()){
        ...
    }
    

    or using the stream directly instead of a for loop:

    string.codePoints().forEach(c -> ...);
    

    There is also CharSequence#chars if you want a stream of the characters (although it is an IntStream, since there is no CharStream).

提交回复
热议问题