Permutate a String to upper and lower case

Francisco picture Francisco · Jul 22, 2011 · Viewed 8.3k times · Source

I have a string, "abc". How would a program look like (if possible, in Java) who permute the String?

For example:

abc
ABC
Abc
aBc
abC
ABc
abC
AbC

Answer

Erik Pilz picture Erik Pilz · Jul 22, 2011

Something like this should do the trick:

void printPermutations(String text) {
  char[] chars = text.toCharArray();
  for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) {
    char[] permutation = new char[chars.length];
    for (int j =0; j < chars.length; j++) {
      permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j];
    }
    System.out.println(permutation);
  }
}

boolean isBitSet(int n, int offset) {
  return (n >> offset & 1) != 0;
}