Javatpoint Logo
Javatpoint Logo

Q. Program to find all possible subsets of a string.

Explanation

In this program, all the subsets of the string need to be printed. The subset of a string is the character or the group of characters that are present inside the string. For example, all possible subsets of a string "FUN" will be F, U, N, FU, UN, FUN.

To complete this program, We need to run two for loops. The outer loop is used to maintain the relative position of the first character and the second loop is used to create all possible subsets and prints them one by one.

The algorithm of the program is given below.

Algorithm

  1. Define a string.
  2. All the possible subsets for a string will be n*(n + 1)/2.
  3. Define a string array with the length of n(n+1)/2. This string array will hold all the subsets of the string.
  4. The first loop will keep the first character of the subset.
  5. The second loop will build the subset by adding one character in each iteration till the end of the string is reached.
    Eg. String "ABC"
    The first loop will hold the position of A, then B then C
    The second loop will subset the string into
    For i=1: A, AB then ABC for the last iteration
    For i=2: B and BC
    For i=3: C
  6. Add the subset formed in each iteration into a string array.
  7. The last loop traverses through all the subset formed and print all the subsets.

Solution

Python

Output:

All subsets for given string are: 
A
AB
ABC
B
BC
C

C

Output:

All subsets for given string are: 
A
AB
ABC
B
BC
C

JAVA

Output:

All subsets for given string are: 
A
AB
ABC
B
BC
C

C#

Output:

All subsets for given string are: 
A
AB
ABC
B
BC
C

PHP

Output:

All subsets for given string are: 
A
AB
ABC
B
BC
C

Next TopicPrograms List





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA