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

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

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

15条回答
  •  再見小時候
    2020-11-22 11:52

    Note most of the other techniques described here break down if you're dealing with characters outside of the BMP (Unicode Basic Multilingual Plane), i.e. code points that are outside of the u0000-uFFFF range. This will only happen rarely, since the code points outside this are mostly assigned to dead languages. But there are some useful characters outside this, for example some code points used for mathematical notation, and some used to encode proper names in Chinese.

    In that case your code will be:

    String str = "....";
    int offset = 0, strLen = str.length();
    while (offset < strLen) {
      int curChar = str.codePointAt(offset);
      offset += Character.charCount(curChar);
      // do something with curChar
    }
    

    The Character.charCount(int) method requires Java 5+.

    Source: http://mindprod.com/jgloss/codepoint.html

提交回复
热议问题