我想根据给定的String创建关于特定定界符的所有可能的连续组合。
例如:
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"};
我该怎么做?不一定要使用分割
答案 0 :(得分:0)
您可以尝试以下方法:
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
答案 1 :(得分:0)
这是您要考虑的另一种选择。这将执行以下操作:
1
是K
的数字时,将数字从K
迭代到2^ntokens -2
。
a,b,c,d
。因此,对于4
,ntoken将为K
,而14
将为1
public static void main(String[] args) {
List<String> tokens = multiSplit("a\\b\\c\\d", "\\\\");
tokens.forEach(System.out::println);
}
public static List<String> multiSplit(String val, String delim) {
String[] sp = val.split(delim);
// temp holding place for combinations
List<String> vals = new ArrayList<>();
// Iterate from 1 to thru 2^ntokens - 1
for (int n = 1; n < ((1 << sp.length) - 1); n++) {
// Using BitSet, determine if n consists of a single string
// of 1 bits.
BitSet bitSet = BitSet.valueOf(new long[] { (long) n
});
int[] indices = bitSet.stream().toArray();
int len = indices.length - 1;
// If the difference of the high indices equal the length of the
// array minus 1, then a single stream has been found.
if (len == indices[len] - indices[0]) {
// create a substring of the source by using the bit positions.
StringBuilder sb = new StringBuilder(sp[indices[0]]);
for (int k = 1; k < indices.length; k++) {
sb.append(delim);
sb.append(sp[indices[k]]);
}
vals.add(sb.toString());
}
}
return vals;
}
的单个位序列的数字
位。{{1}}