In this article, we will understand how to find all the subsets of a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”). A part or a subset of string is called substring.
Below is a demonstration of the same −
Suppose our input is −
The string is defined as: JVM
The desired output would be −
The subsets of the string are: J JV JVM V VM M
Algorithm
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Initialize a temporary variable to increment after every iteration. Step 5 - Iterate through the length of the string using two nested loops. Step 6 - Find substring between a given range, and increment the temporary variable after every iteration. Step 7 - Display the substrings using a loop. Step 8 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class Demo { public static void main(String[] args) { String input_string = "JVM"; int string_length = input_string.length(); int temp = 0; System.out.println("The string is defined as: " +input_string); String string_array[] = new String[string_length*(string_length+1)/2]; for(int i = 0; i < string_length; i++) { for(int j = i; j < string_length; j++) { string_array[temp] = input_string.substring(i, j+1); temp++; } } System.out.println("The subsets of the string are: "); for(int i = 0; i < string_array.length; i++) { System.out.println(string_array[i]); } } }
Output
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class Demo { static void subsets(String input_string){ int string_length = input_string.length(); int temp = 0; String string_array[] = new String[string_length*(string_length+1)/2]; for(int i = 0; i < string_length; i++) { for(int j = i; j < string_length; j++) { string_array[temp] = input_string.substring(i, j+1); temp++; } } System.out.println("The subsets of the string are: "); for(int i = 0; i < string_array.length; i++) { System.out.println(string_array[i]); } } public static void main(String[] args) { String input_string = "JVM"; System.out.println("The string is defined as: " +input_string); subsets(input_string); } }
Output
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M