根据字符串定界符从字符串中获取子字符串列表
Get list of the substring from the string based on the String delimiter
String s = "I like an orange as well as apple but mostly apple. apple, orange are the best fruits.";
String[] delimiter = {"orange", "apple"};
我想像下面这样拆分这个字符串:
{"I like an ", "orange", " as well as ", "apple", " but mostly ", "apple", ".", "apple", ",", "orange", " are the best fruits."}
上面我根据水果orange和apple拆分了字符串,但是这两个水果也是子字符串列表的一部分。
使用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 + "}");
}
}
}
String s = "I like an orange as well as apple but mostly apple. apple, orange are the best fruits.";
String[] delimiter = {"orange", "apple"};
我想像下面这样拆分这个字符串:
{"I like an ", "orange", " as well as ", "apple", " but mostly ", "apple", ".", "apple", ",", "orange", " are the best fruits."}
上面我根据水果orange和apple拆分了字符串,但是这两个水果也是子字符串列表的一部分。
使用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 + "}");
}
}
}