实测比 String 的 split() 方法快 3 倍以上的字符串简易分割方法,stringsplit,对于字符串分隔,在 Ja
分享于 点击 26549 次 点评:246
实测比 String 的 split() 方法快 3 倍以上的字符串简易分割方法,stringsplit,对于字符串分隔,在 Ja
对于字符串分隔,在 Java 6.0 以内,都只提供了支持正则表达式的 split()一套方法。对于简单的分割,正则表达式消耗了一半以上的运算资源。先考虑大规模计算中频繁用到的字符串分割,自制了一个方法,通过取出 char[],逐一判断是否是分割用的字符,通过 System.arraycopy 取出一个个字符数组,生成字符串,存放进一个 LinkedList 里边。
如果规模比较大,拟考虑通过二重循环,用 String[] 作为结果收集器。
static public List<String> splitSimpleString(String source, char gap){ List<String> result = new LinkedList<String>(); if (source == null) return result; char[] sourceChars = source.toCharArray(); int startIndex = 0, index = -1; while (index++ != sourceChars.length) { if (index == sourceChars.length || sourceChars[index] == gap) { char[] section = new char[index - startIndex]; System.arraycopy(sourceChars, startIndex, section, 0, index - startIndex); result.add(String.valueOf(section)); startIndex = index + 1; } } return result;}//该片段来自于http://byrx.net
用户点评