Here is a recursive solution that works. I used a List<List<String>>
rather than a 2-dimensional array to make things easier. The code is a bit ugly and could probably be tidied up a little.
Sample output:
$ 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) {
// 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);
}
}
}
}