Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Split a string until a certain string occurs a certain amount of times
- */
- public static String[] splitUntilOccurrence(String source, String split, String until, int occurrence) {
- int untilIndex = -1;
- if (occurrence >= 0) {
- untilIndex = source.indexOf(until);
- }
- for (int i = 0; i < occurrence; i++) {
- untilIndex = source.indexOf(until, untilIndex + until.length());
- }
- if (untilIndex <= 0 || untilIndex >= source.length()) {
- return source.split(split);
- }
- String toSplit = source.substring(0, untilIndex);
- String remainder = source.substring(untilIndex + until.length());
- String[] splitted = toSplit.split(split);
- String[] out = new String[splitted.length + 1];
- System.arraycopy(splitted, 0, out, 0, splitted.length);
- out[out.length - 1] = remainder;
- return out;
- }
- /**
- * Split a string until a certain string occurs a certain amount of times after another certain string occurs a certain amount of times
- */
- public static String[] splitUntilOccurenceAfterOccurence(String source, String split, String until, int occurrence, String after, int afterOccurrence) {
- if (occurrence < 0) {
- return source.split(split);
- }
- int afterIndex = -1;
- if (afterOccurrence >= 0) {
- afterIndex = source.indexOf(after);
- }
- for (int i = 0; i < afterOccurrence; i++) {
- afterIndex = source.indexOf(after, afterIndex + after.length());
- }
- if (afterIndex <= 0 || afterIndex >= source.length()) {
- return source.split(split);
- }
- int occurenceCountUntilAfter = 0;
- int untilIndex = source.indexOf(until);
- while (untilIndex != -1 && untilIndex < afterIndex + after.length()) {
- untilIndex = source.indexOf(until, untilIndex + until.length());
- occurenceCountUntilAfter++;
- }
- return splitUntilOccurrence(source, split, until, occurenceCountUntilAfter + occurrence);
- }
Advertisement
Add Comment
Please, Sign In to add comment