diff --git a/src/zutil/StringUtil.java b/src/zutil/StringUtil.java index 814b626..6cc454a 100755 --- a/src/zutil/StringUtil.java +++ b/src/zutil/StringUtil.java @@ -28,6 +28,7 @@ import zutil.converter.Converter; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; /** * This is a class whit utility methods. @@ -214,4 +215,29 @@ public class StringUtil { } return SPACES.get(i); } + + + /** + * A simple split method that uses {@link String#substring(int, int)} + * to split a string between a single character delimiter. + * This method should be used for performance reasons as it is faster than + * the {@link String#split(String)}. + * + * @param str is the string to be split + * @param delimiter a single character delimiter + * @return a List with all data between the delimiter + */ + public static List split(String str, char delimiter){ + ArrayList splitList = new ArrayList<>(); + int from = 0, to = 0; + while (to >= 0) { + to = str.indexOf(delimiter, from + 1); + if (to < 0) + splitList.add(str.substring(from)); + else + splitList.add(str.substring(from, to)); + from = to; + } + return splitList; + } } diff --git a/test/zutil/benchmark/StringSplitBenchmark.java b/test/zutil/benchmark/StringSplitBenchmark.java index e627625..648f4be 100755 --- a/test/zutil/benchmark/StringSplitBenchmark.java +++ b/test/zutil/benchmark/StringSplitBenchmark.java @@ -4,8 +4,10 @@ import com.carrotsearch.junitbenchmarks.BenchmarkOptions; import com.carrotsearch.junitbenchmarks.BenchmarkRule; import org.junit.Rule; import org.junit.Test; +import zutil.StringUtil; import java.util.ArrayList; +import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; @@ -39,16 +41,7 @@ public class StringSplitBenchmark { @Test public void substring(){ for(int i=0; i splitList = new ArrayList<>(); - int from = 0, to = 0; - while (to >= 0) { - to = str.indexOf(delimiter, from + 1); - if (to < 0) - splitList.add(str.substring(from)); - else - splitList.add(str.substring(from, to)); - from = to; - } + List splitList = StringUtil.split(str, delimiter.charAt(0)); assertSplit(splitList.toArray(new String[splitList.size()])); } }