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

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

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

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 11:50

    Elaborating on this answer and this answer.

    Above answers point out the problem of many of the solutions here which don't iterate by code point value -- they would have trouble with any surrogate chars. The java docs also outline the issue here (see "Unicode Character Representations"). Anyhow, here's some code that uses some actual surrogate chars from the supplementary Unicode set, and converts them back to a String. Note that .toChars() returns an array of chars: if you're dealing with surrogates, you'll necessarily have two chars. This code should work for any Unicode character.

        String supplementary = "Some Supplementary: 

提交回复
热议问题