See the following code to generate all string permutations:-
//Taking string which have to generate the permutations.
private static void allPermutations(String str) {
generateAllPermutations(str.toCharArray(), 0);
}
//Generates all permutations of string
private static void generateAllPermutations(char[] ch, int currentIndex) {
if(currentIndex == ch.length-1) {
System.out.println(String.copyValueOf(ch));
}
for(int i=currentIndex; i<ch.length; i++) {
swap(ch, currentIndex, i);
generateAllPermutations(ch, currentIndex+1);
swap(ch, currentIndex, i);
}
}
//Swap character
private static void swap(char[] ch, int currentIndex, int i) {
char tmp = ch[currentIndex];
ch[currentIndex] = ch[i];
ch[i] = tmp;
}
Output:-
Permutations:-
abc
acb
bac
bca
cba
cab