最近遇到一个需求,最后抽象出来是一个字符串切割问题,将类似这句话:
${a}总部位于中国${b}自由贸易${c}${c}验区,依法从事商${d}${b}期货经纪、金融期货经纪${a}${a}期货交易${a}
切割成这样:
[${a}, 总部位于中国, ${b}, 自由贸易, ${c}, ${c}, 验区,依法从事商, ${d}, ${b}, 期货经纪、金融期货经纪, ${a}, ${a}, 期货交易, ${a}]
public class SplitStr {
public static void main(String[] args) {
String content = "${a}总部位于中国${b}" +
"自由贸易${c}${c}验区,依法从事商${d}${b}期货经纪、金融期货经纪" +
"${a}${a}期货交易${a}";
String[] split = content.split("\\$\\{a}|\\$\\{b}|\\$\\{c}|\\$\\{d}");
System.out.println(content);
List<String> result = new ArrayList<>();
for (String str : split) {
if (str.length() >= 1)
result.add(str);
Map<String, Object> map = findFirstVariableAndIndex(content);
String variable = (String) map.get("variable");
if (variable.length() >= 1)
result.add(variable);
content = content.substring(str.length() + variable.length());
}
System.out.println(result);
}
private static Map<String, Object> findFirstVariableAndIndex(String content) {
Map<String, Object> map = new HashMap<>();
Set<String> set = new HashSet<>();
set.add("${a}");
set.add("${b}");
set.add("${c}");
set.add("${d}");
int minVariableIndex = Integer.MAX_VALUE;
String variable = "";
for (String key : set) {
int index = content.indexOf(key);
if (index >= 0 && index < minVariableIndex) {
variable = key;
minVariableIndex = index;
}
}
map.put("variable", variable);
map.put("minVariableIndex", minVariableIndex);
return map;
}
}
ret:
${a}总部位于中国${b}自由贸易${c}${c}验区,依法从事商${d}${b}期货经纪、金融期货经纪${a}${a}期货交易${a}
[${a}, 总部位于中国, ${b}, 自由贸易, ${c}, ${c}, 验区,依法从事商, ${d}, ${b}, 期货经纪、金融期货经纪, ${a}, ${a}, 期货交易, ${a}]