Here is the recursive solution in which it works . I used List<List<String>>instead of a 2-dimensional array to simplify the task. The code is a little ugly and probably can be a bit tidy.
Output Example:
$ 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]
code:
import java.util.*;
public class Main {
public static void main(String[] 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>>();
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()) {
currentResult.add(sb.toString());
resultsSoFar.add(currentResult);
} else {
char c = str.charAt(pos);
if (c == ' ' || c == '-') {
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);
}
}
}
}