String.split() *not* on regular expression?

前端 未结 8 928
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 04:31

Since String.split() works with regular expressions, this snippet:

String s = \"str?str?argh\";
s.split(\"r?\");

... yields: <

8条回答
  •  日久生厌
    2020-12-03 05:02

    This works perfect as well:

    public static List splitNonRegex(String input, String delim)
    {
        List l = new ArrayList();
        int offset = 0;
    
        while (true)
        {
            int index = input.indexOf(delim, offset);
            if (index == -1)
            {
                l.add(input.substring(offset));
                return l;
            } else
            {
                l.add(input.substring(offset, index));
                offset = (index + delim.length());
            }
        }
    }
    

提交回复
热议问题