これは機能する再帰的なソリューションです。List<List<String>>
作業を簡単にするために、2 次元配列ではなく配列を使用しました。コードは少し醜いので、おそらく少し整理することができます。
出力例:
$ java Main foo bar-baz-zzz
Processing: foo bar-baz-zzz
[foo, bar, baz, zzz]
[foo, bar, baz-zzz]
[foo, bar-baz, zzz]
[foo, bar-baz-zzz]
[foo bar, baz, zzz]
[foo bar, baz-zzz]
[foo bar-baz, zzz]
[foo bar-baz-zzz]
コード:
import java.util.*;
public class Main {
public static void main(String[] args) {
// First build a single string from the command line args.
StringBuilder sb = new StringBuilder();
Iterator<String> it = Arrays.asList(args).iterator();
while (it.hasNext()) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(' ');
}
}
process(sb.toString());
}
protected static void process(String str) {
System.err.println("Processing: " + str);
List<List<String>> results = new LinkedList<List<String>>();
// Invoke the recursive method that does the magic.
process(str, 0, results, new LinkedList<String>(), new StringBuilder());
for (List<String> result : results) {
System.err.println(result);
}
}
protected static void process(String str, int pos, List<List<String>> resultsSoFar, List<String> currentResult, StringBuilder sb) {
if (pos == str.length()) {
// Base case: Reached end of string so add buffer contents to current result
// and add current result to resultsSoFar.
currentResult.add(sb.toString());
resultsSoFar.add(currentResult);
} else {
// Step case: Inspect character at pos and then make recursive call.
char c = str.charAt(pos);
if (c == ' ' || c == '-') {
// When we encounter a ' ' or '-' we recurse twice; once where we treat
// the character as a delimiter and once where we treat it as a 'normal'
// character.
List<String> copy = new LinkedList<String>(currentResult);
copy.add(sb.toString());
process(str, pos + 1, resultsSoFar, copy, new StringBuilder());
sb.append(c);
process(str, pos + 1, resultsSoFar, currentResult, sb);
} else {
sb.append(c);
process(str, pos + 1, resultsSoFar, currentResult, sb);
}
}
}
}