In this article, you will learn how to write a java program to find all subsets of a String. If the number of characters in a given string is n then the number of possible subsets of that string would be: n(n+1)/2. For example: if the length of a string is 4 then the number of subsets would be: 4(4+1)/2 = 10.
A String “TOY” has 3(3+1)/2 = 6 subset strings: “T”, “O”, “Y”, “TO”, “OY”, “TOY”.
Java Program to Find all subsets of a String
Steps followed in the example are:
- Find the length of the given string using length() method.
- Create a String array to hold all the subsets of the given string, size of the array would be n(n+1)/2.
- Inside nested for loop use substring() method to find all the possible subsets of the string. Store them in the array created in the step 2.
- loop the array and print all the elements to display all the subsets.
public class JavaExample {
public static void main(String[] args) {
String str = "TEXT";
//finding length of the given string
int numberOfChar = str.length();
int temp = 0;
//If number of characters in a string is n then the
//possible subsets of that string is n*(n+1)/2
String subsetArray[] = new String[numberOfChar*(numberOfChar+1)/2];
for(int i = 0; i < numberOfChar; i++) {
for(int j = i; j < numberOfChar; j++) {
subsetArray[temp] = str.substring(i, j+1);
temp++;
}
}
//Print all the subsets of the given string
System.out.println("All the possible subsets of the given string: ");
for(int i = 0; i < subsetArray.length; i++) {
System.out.println(subsetArray[i]);
}
}
}
Output:
Leave a Reply