String s = "I like an orange as well as apple but mostly apple. apple, orange are the best fruits.";
String[] delimiter = {"orange", "apple"};
I wanted to split this string like below:
{"I like an ", "orange", " as well as ", "apple", " but mostly ", "apple", ".", "apple", ",", "orange", " are the best fruits."}
In above, I have split the string based on the fruit orange and apple, but both the fruits are also the part of list of substring.
CodePudding user response:
Using this answer:
public class Solution {
public static String[] getTokens(String str, String[] delimeters) {
if (delimeters.length == 0) {
return new String[]{str};
}
// Create regex: ((?<=delimeter)|(?=delimeter))
String delimetersConcatenatedWithOr = "(" String.join(")|(", delimeters) ")";
String regex = "((?<=" delimetersConcatenatedWithOr ")|(?=" delimetersConcatenatedWithOr "))";
// Split using regex
return str.split(regex);
}
public static void main(String args[]) {
String str = "I like an orange as well as apple but mostly apple. apple, orange are the best fruits.";
String[] delimeters = {"apple", "orange"};
for (String token : getTokens(str, delimeters)) {
System.out.println("{" token "}");
}
}
}