Created
September 29, 2016 14:32
-
-
Save dwairi/0d0ea3022a18c2dcd3ee72c4e60ba6cb to your computer and use it in GitHub Desktop.
walk a string and separate it based on separator and a marker that is supposed to be in every string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class CustomStringSplit { | |
public static void main(String[] args) { | |
String string = "Key1==value1; key2==val;ue2;key3==value3"; | |
String separator = ";"; | |
String marker = "=="; | |
List<String> splitted = Split(string, separator, marker); | |
for (String element : splitted) { | |
System.out.println(element); | |
} | |
} | |
private static List<String> Split(String string, String separator, String marker) { | |
List<String> list = new ArrayList<String>(); | |
int start = 0; | |
int endIndex = string.indexOf(separator); | |
String previousString = null; | |
while (endIndex != -1) { | |
String str = string.substring(start, endIndex); | |
if (previousString != null && !str.contains(marker)) { | |
list.remove(list.size() - 1); | |
list.add(previousString + str); | |
start = start + str.length(); | |
endIndex = string.indexOf(separator, start + 1); | |
previousString = previousString + str; | |
continue; | |
} | |
previousString = str; | |
start = string.indexOf(separator, start + str.length()); | |
endIndex = string.indexOf(separator, start + 1); | |
list.add(str.trim()); | |
} | |
list.add(string.substring(start)); | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment