Scanner vs. StringTokenizer vs. String.Split

前端 未结 10 1278
太阳男子
太阳男子 2020-11-22 10:56

I just learned about Java\'s Scanner class and now I\'m wondering how it compares/competes with the StringTokenizer and String.Split. I know that the StringTokenizer and Str

10条回答
  •  日久生厌
    2020-11-22 11:37

    For the default scenarios I would suggest Pattern.split() as well but if you need maximum performance (especially on Android all solutions I tested are quite slow) and you only need to split by a single char, I now use my own method:

    public static ArrayList splitBySingleChar(final char[] s,
            final char splitChar) {
        final ArrayList result = new ArrayList();
        final int length = s.length;
        int offset = 0;
        int count = 0;
        for (int i = 0; i < length; i++) {
            if (s[i] == splitChar) {
                if (count > 0) {
                    result.add(new String(s, offset, count));
                }
                offset = i + 1;
                count = 0;
            } else {
                count++;
            }
        }
        if (count > 0) {
            result.add(new String(s, offset, count));
        }
        return result;
    }
    

    Use "abc".toCharArray() to get the char array for a String. For example:

    String s = "     a bb   ccc  ffffdd eeeee  ffffff    ggggggg ";
    ArrayList result = splitBySingleChar(s.toCharArray(), ' ');
    

提交回复
热议问题