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

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

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

15条回答
  •  执笔经年
    2020-11-22 11:30

    Two options

    for(int i = 0, n = s.length() ; i < n ; i++) { 
        char c = s.charAt(i); 
    }
    

    or

    for(char c : s.toCharArray()) {
        // process c
    }
    

    The first is probably faster, then 2nd is probably more readable.

提交回复
热议问题