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

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

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

15条回答
  •  耶瑟儿~
    2020-11-22 11:46

    If you have Guava on your classpath, the following is a pretty readable alternative. Guava even has a fairly sensible custom List implementation for this case, so this shouldn't be inefficient.

    for(char c : Lists.charactersOf(yourString)) {
        // Do whatever you want     
    }
    

    UPDATE: As @Alex noted, with Java 8 there's also CharSequence#chars to use. Even the type is IntStream, so it can be mapped to chars like:

    yourString.chars()
            .mapToObj(c -> Character.valueOf((char) c))
            .forEach(c -> System.out.println(c)); // Or whatever you want
    

提交回复
热议问题