How to split a string, but also keep the delimiters?

前端 未结 23 2777
我在风中等你
我在风中等你 2020-11-21 06:32

I have a multiline string which is delimited by a set of different delimiters:

(Text1)(DelimiterA)(Text2)(DelimiterC)(Text3)(DelimiterB)(Text4)
23条回答
  •  生来不讨喜
    2020-11-21 06:44

    I don't know of an existing function in the Java API that does this (which is not to say it doesn't exist), but here's my own implementation (one or more delimiters will be returned as a single token; if you want each delimiter to be returned as a separate token, it will need a bit of adaptation):

    static String[] splitWithDelimiters(String s) {
        if (s == null || s.length() == 0) {
            return new String[0];
        }
        LinkedList result = new LinkedList();
        StringBuilder sb = null;
        boolean wasLetterOrDigit = !Character.isLetterOrDigit(s.charAt(0));
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c) ^ wasLetterOrDigit) {
                if (sb != null) {
                    result.add(sb.toString());
                }
                sb = new StringBuilder();
                wasLetterOrDigit = !wasLetterOrDigit;
            }
            sb.append(c);
        }
        result.add(sb.toString());
        return result.toArray(new String[0]);
    }
    

提交回复
热议问题