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

前端 未结 15 1219
挽巷
挽巷 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:                                                                     
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 11:54

    There are some dedicated classes for this:

    import java.text.*;
    
    final CharacterIterator it = new StringCharacterIterator(s);
    for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
       // process c
       ...
    }
    
    0 讨论(0)
提交回复
热议问题