Guest User

Untitled

a guest
Jan 30th, 2013
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1.     /**
  2.      * Split a string until a certain string occurs a certain amount of times
  3.      */
  4.     public static String[] splitUntilOccurrence(String source, String split, String until, int occurrence) {
  5.         int untilIndex = -1;
  6.         if (occurrence >= 0) {
  7.             untilIndex = source.indexOf(until);
  8.         }
  9.         for (int i = 0; i < occurrence; i++) {
  10.             untilIndex = source.indexOf(until, untilIndex + until.length());
  11.         }
  12.         if (untilIndex <= 0 || untilIndex >= source.length()) {
  13.             return source.split(split);
  14.         }
  15.         String toSplit = source.substring(0, untilIndex);
  16.         String remainder = source.substring(untilIndex + until.length());
  17.         String[] splitted = toSplit.split(split);
  18.  
  19.         String[] out = new String[splitted.length + 1];
  20.  
  21.         System.arraycopy(splitted, 0, out, 0, splitted.length);
  22.         out[out.length - 1] = remainder;
  23.  
  24.         return out;
  25.     }
  26.  
  27.     /**
  28.      * Split a string until a certain string occurs a certain amount of times after another certain string occurs a certain amount of times
  29.      */
  30.     public static String[] splitUntilOccurenceAfterOccurence(String source, String split, String until, int occurrence, String after, int afterOccurrence) {
  31.         if (occurrence < 0) {
  32.             return source.split(split);
  33.         }
  34.         int afterIndex = -1;
  35.         if (afterOccurrence >= 0) {
  36.             afterIndex = source.indexOf(after);
  37.         }
  38.         for (int i = 0; i < afterOccurrence; i++) {
  39.             afterIndex = source.indexOf(after, afterIndex + after.length());
  40.         }
  41.         if (afterIndex <= 0 || afterIndex >= source.length()) {
  42.             return source.split(split);
  43.         }
  44.         int occurenceCountUntilAfter = 0;
  45.         int untilIndex = source.indexOf(until);
  46.         while (untilIndex != -1 && untilIndex < afterIndex + after.length()) {
  47.             untilIndex = source.indexOf(until, untilIndex + until.length());
  48.             occurenceCountUntilAfter++;
  49.         }
  50.         return splitUntilOccurrence(source, split, until, occurenceCountUntilAfter + occurrence);
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment