java - 如何将字符串拆分为关于特定分隔符的所有可能的连续组合
问题描述
我想从给定的字符串创建关于特定分隔符的所有可能的连续组合。
例如:
String s = "a\\b\\c\\d"
和String delimiter = "\\\\"
使用
`String[] split = s.split(delimiter);`
返回
`{"a","b","c","d"}`
但我想得到:
{"a","b","c","d","a\\b","b\\c","c\\d","a\\b\\c","b\\c\\d"};
我怎样才能做到这一点?不一定使用拆分
解决方案
你可以试试这个:
import java.util.ArrayList;
import java.util.List;
public class CombinationSplit {
public static void main(String[] args) {
List<String> split = split("a\\b\\c\\d", "\\\\");
for (String s : split) {
System.out.println(s);
}
}
private static List<String> split(String s, String delimiter) {
String[] split = s.split(delimiter);
List<String> output = new ArrayList<>();
for (int i = 1; i < split.length; i++) {
int[][] combinations = consecutiveCombinations(split.length, i);
for (int[] combination : combinations) {
output.add(glue(split, combination, delimiter));
}
}
return output;
}
private static String glue(String[] string, int[] indices, String delimiter) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0, indicesLength = indices.length; i < indicesLength - 1; i++) {
int index = indices[i];
stringBuilder.append(string[index]);
stringBuilder.append(delimiter);
}
stringBuilder.append(string[indices[indices.length - 1]]);
return stringBuilder.toString();
}
private static int[][] consecutiveCombinations(int n, int k) {
int count = n - k + 1;
int[][] output = new int[count][k];
for (int i = 0; i < count; i++) {
int[] path = new int[k];
for (int j = 0; j < k; j++) {
path[j] = i + j;
}
output[i] = path;
}
return output;
}
}
输出:
a
b
c
d
a\\b
b\\c
c\\d
a\\b\\c
b\\c\\d
推荐阅读
- python - 无法使用 time.sleep() 解决 HTTP 错误 429
- google-chrome - GalliumOS 上的 Google Chrome 版本 80 在几个小时后可靠地崩溃
- c++11 - 模板成员函数中的 lambda 错误
- pyspark - 使用 Pyspark DataFrames 和 JDBC 在 RDBMS(Mysql) 表中进行 Upsert
- javascript - 为什么在发布请求离开 div 后会检索值?
- centos - 如何使用 YUM 在 CentOS 中安装多个版本的兼容软件包
- css - 如何让div大时在左边,小时在底部?
- java - 如何使用 shell 脚本运行 jar 并等待其完成然后执行其他任务
- unity3d - Unity AR Foundation 对象锚点问题
- html - 为什么调整大小后flex中的`text-align:center`会破坏布局?