Permutate a String to upper and lower case

帅比萌擦擦* 提交于 2019-12-04 11:47:36

问题


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

回答1:


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;
}



回答2:


As you probably already know, the number of possible different combinations is 2^n, where n equals the length of the input string.

Since n could theoretically be fairly large, there's a chance that 2^n will exceed the capacity of a primitive type such as an int. (The user may have to wait a few years for all of the combinations to finish printing, but that's their business.)

Instead, let's use a bit vector to hold all of the possible combinations. We'll set the number of bits equal to n and initialize them all to 1. For example, if the input string is "abcdefghij", the initial bit vector values will be {1111111111}.

For every combination, we simply have to loop through all of the characters in the input string and set each one to uppercase if its corresponding bit is a 1, else set it to lowercase. We then decrement the bit vector and repeat.

For example, the process would look like this for an input of "abc":

Bits:   Corresponding Combo:
111    ABC
110    ABc
101    AbC
100    Abc
011    aBC
010    aBc
001    abC
000    abc

By using a loop rather than a recursive function call, we also avoid the possibility of a stack overflow exception occurring on large input strings.

Here is the actual implementation:

import java.util.BitSet;

public void PrintCombinations(String input) {
    char[] currentCombo = input.toCharArray();

    // Create a bit vector the same length as the input, and set all of the bits to 1
    BitSet bv = new BitSet(input.length());
    bv.set(0, currentCombo.length);

    // While the bit vector still has some bits set
    while(!bv.isEmpty()) {
        // Loop through the array of characters and set each one to uppercase or lowercase, 
        // depending on whether its corresponding bit is set
        for(int i = 0; i < currentCombo.length; ++i) {
            if(bv.get(i)) // If the bit is set
                currentCombo[i] = Character.toUpperCase(currentCombo[i]);
            else
                currentCombo[i] = Character.toLowerCase(currentCombo[i]);
        }

        // Print the current combination
        System.out.println(currentCombo);

        // Decrement the bit vector
        DecrementBitVector(bv, currentCombo.length);            
    }

    // Now the bit vector contains all zeroes, which corresponds to all of the letters being lowercase.
    // Simply print the input as lowercase for the final combination
    System.out.println(input.toLowerCase());        
}


public void DecrementBitVector(BitSet bv, int numberOfBits) {
    int currentBit = numberOfBits - 1;          
    while(currentBit >= 0) {
        bv.flip(currentBit);

        // If the bit became a 0 when we flipped it, then we're done. 
        // Otherwise we have to continue flipping bits
        if(!bv.get(currentBit))
            break;
        currentBit--;
    }
}



回答3:


String str = "Abc";
str = str.toLowerCase();
int numOfCombos = 1 << str.length();  

for (int i = 0; i < numOfCombos; i++) {

    char[] combinations = str.toCharArray();
    for (int j = 0; j < str.length(); j++) {

        if (((i >> j) & 1) == 1 ) {
            combinations[j] = Character.toUpperCase(str.charAt(j));
        }

    }
    System.out.println(new String(combinations));
}



回答4:


Please find here the code snippet for the above :

public class StringPerm {
public static void main(String[] args) {
    String str = "abc";
    String[] f = permute(str);

    for (int x = 0; x < f.length; x++) {
        System.out.println(f[x]);
    }

}

public static String[] permute(String str) {
    String low = str.toLowerCase();
    String up = str.toUpperCase();

    char[] l = low.toCharArray();

    char u[] = up.toCharArray();

    String[] f = new String[10];
    f[0] = low;
    f[1] = up;
    int k = 2;

    char[] temp = new char[low.length()];

    for (int i = 0; i < l.length; i++) 
    {
        temp[i] = l[i]; 

        for (int j = 0; j < u.length; j++) 
        {
            if (i != j) {
                temp[j] = u[j];
            }
        }

        f[k] = new String(temp);
        k++;
    }

    for (int i = 0; i < u.length; i++) 
    {
        temp[i] = u[i];         

        for (int j = 0; j < l.length; j++) 
        {
            if (i != j) {
                temp[j] = l[j];
            }
        }

        f[k] = new String(temp);
        k++;
    }

    return f;
}

}




回答5:


You can do something like

```

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
        String n=(args[0]);
        HashSet<String>rs = new HashSet();
        helper(rs,n,0,n.length()-1);

        System.out.println(rs);
    }
    public static void helper(HashSet<String>rs,String res , int l, int n)
    {
        if(l>n)
        return;

        for(int i=l;i<=n;i++)
        {

            res=swap(res,i);
            rs.add(res);
            helper(rs,res,l+1,n);
            res=swap(res,i);
        }

    }
    public static String swap(String st,int i)
    {
        char c = st.charAt(i);

        char ch[]=st.toCharArray();
        if(Character.isUpperCase(c))
        {
            c=Character.toLowerCase(c);
        }
        else if(Character.isLowerCase(c))
        {
            c=Character.toUpperCase(c);
        }
        ch[i]=c;
        return new String(ch);
    }

}

```



来源:https://stackoverflow.com/questions/6785358/permutate-a-string-to-upper-and-lower-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!