This solution
generates different combinations of words separated by a delimiter.
If input is
provided as Word1,Word2,Word3 and delimiter is provided as , then
output will be
Word1
Word2
Word3
Word1,Word2
Word1,Word3
Word2,Word3
Word1,Word2,Word3
import java.util.StringTokenizer; public class WordPermutation { String input; //input String StringBuffer output; //Holds the output String delimiter = ","; //Delimiter (default comma (,)) String arrayOfWords[]; /* * Generates combinations by applying the * concept of recursion */ private void nextCombination(int position, int remainder) { output.append(arrayOfWords[position]+this.delimiter); if (remainder == 1) { System.out.println(output.substring(0,output.length()-1)); } else { for (int i = position + 1; i + remainder - 1 <= arrayOfWords.length; i++) nextCombination(i, remainder - 1); } output.delete(output.indexOf(arrayOfWords[position]),output.length()); } public void generateCombinations(String input, String delimiter) { output = new StringBuffer(); this.input = input; this.delimiter = delimiter; /* * Splitting the words by delimiter and storing in * an array. */ StringTokenizer buf = new StringTokenizer(input,delimiter); int lengthOfArray = buf.countTokens(); arrayOfWords = new String[lengthOfArray]; int i = 0; while(buf.hasMoreTokens()) { arrayOfWords[i] = buf.nextToken(); i++; } for (int j = 1; j <= lengthOfArray; j++) for (int k = 0; k + j <= lengthOfArray; k++) { nextCombination(k, j); } } public void generateCombinations(String input) { generateCombinations(input, this.delimiter); } /** * @param args */ public static void main(String[] args) { new WordPermutation().generateCombinations("SR$WB","$"); } }