# All possible strings of any length that can be formed from a given string?

CServer Side ProgrammingProgramming

In this section we will see how to generate all possible strings of any length, this will take each combination of characters to make string. For example, if the string is ABC, then it will generate − {A, B, C, AB, BA, BC, CB, CA, AC, ABC, ACB, BAC, BCA, CAB, CBA}

Let us see the example to get the idea.

## Algorithm

#### printAllString(str)

Begin
n := length of the string str
count is 2^n – 1
for each number 0 to count, do
sub_str := empty string
for j in range 0 to n, do
if jth bit of the counter is set, then
concatenate jth character of str with sub_str
end if
done
repeat:
print sub_string
until next permutation of sub_string is not completed
done
End

## Example

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
void printAllString(string str) {
int n = str.size();
unsigned int count = pow(2, n);
for (int counter = 1; counter <count; counter++) { //generate 2^n - 1 strings
string subs = "";
for (int j = 0; j < n; j++) {
if (counter & (1<<j)) //when the jth bit is set, then add jth character
subs.push_back(str[j]);
}
do{
cout << subs << endl;
}
while (next_permutation(subs.begin(), subs.end()));
}
}

## Output

A
B
AB
BA
C
AC
CA
BC
CB
ABC
ACB
BAC
BCA
CAB
CBA
D
DA
BD
DB
ABD
BDA
DAB
DBA
CD
DC
ACD
CDA
DAC
DCA
BCD
BDC
CBD
CDB
DBC
DCB
ABCD
ABDC
ACBD
ACDB
BACD
BCDA
BDAC
BDCA
CABD
DCBA