You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level3 programs in java (advanced)
In this core java programming tutorial we will write a program to print all combinations of String by placing space in between in java.
Example 1 in java >
When ABC is passed
output is -
ABC
AB C
A BC
A B C
Example 2 in java >
When ABCD is passed
output is -
ABCD
ABC D
AB CD
AB C D
A BCD
A BC D
A B CD
A B C D
Key to solve program is recursion, for better understanding of program I’ll recommend developers to debug this program carefully in eclipse.
Full Program/SourceCode/ Example to to print all combinations of String by placing space in between in java >
/** JavaMadeSoEasy.com */
public class PrintAllCombinationWithSpaceInBetween{
public static void main(String[] args) {
String str = "ABC";
char[] ar = str.toCharArray();
//Keep tempAr size double-1 than original
//So that it could hold String like "A B C"
char[] tempAr = new char[(2 * ar.length)-1];
tempAr[0] = ar[0];
getCombinations(ar, tempAr, 1, 1, ar.length);
}
public static void getCombinations(char[] ar, char[] tempAr, int i, int j,int len) {
if (i == len) {
while (j < tempAr.length) {
tempAr[j] = ' ';
j++;
}
System.out.println(tempAr);
return;
}
tempAr[j] = ar[i];
getCombinations(ar, tempAr, i + 1, j + 1, len);
tempAr[j] = ' ';
tempAr[j + 1] = ar[i];
getCombinations(ar, tempAr, i + 1, j + 2, len);
return;
}
}
/*Output
ABC
AB C
A BC
A B C
*/
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>