bobmarley12345

Java ultra fast split(String, String)

Dec 24th, 2022
1,125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. /**
  2.  * Splits the given string by the given splitter string, keeping empty strings
  3.  * if there are zero characters between splits
  4.  * @param string The input string to split
  5.  * @param split  The splitter value
  6.  * @return A list of split elements
  7.  * @author REghZy
  8.  */
  9. @Nonnull
  10. public static ArrayList<String> splitAsList(@Nullable String string, @Nullable String split) {
  11.     int srcLen, tarLen;
  12.     if (string == null || (srcLen = string.length()) == 0)
  13.         return new ArrayList<String>();
  14.     if (split == null || (tarLen = split.length()) == 0)
  15.         return Linq.of(charToStringArray(string.toCharArray())).toList();
  16.     ArrayList<String> list = new ArrayList<String>();
  17.     int i = -tarLen, last = 0;
  18.     while ((i = string.indexOf(split, i + tarLen)) != -1) {
  19.         list.add(string.substring(last, i));
  20.         last = i + tarLen;
  21.     }
  22.     // using '<=' instead of '<' to keep the empty string element if the split is
  23.     // at the very end of the string (because 'last' will be equal to 'srcLen' in this case)
  24.     // e.g. splitAsList("hi__lol__") with '<=' gives ["hi", "lol", ""], whereas '<' gives ["hi", "lol"]
  25.     // Could add a "keepTrailingSplits" parameter, and replace below with (keepTrailingSplits ? (last <= srcLen) : (last < srcLen))
  26.     if (last <= srcLen) {
  27.         list.add(string.substring(last));
  28.     }
  29.     return list;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment