Find All Subsets of a String in Java



In this article, we will understand how to find all the subsets of a string. In Java, 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.

Example Scenario:

Input: string = JVM;
Output: The subsets of the string are: J, JV, JVM, V, VM, M 

Finding all Subsets of a String in Java

Use the following approaches to find all subsets of a String in Java ?

  • Using nested for Loop
  • Using substring() method

Using nested for Loop

In this approach, we use the nested for loop. The outer loop will run till the number of subset and inner loop will run till the string length. Inside the inner loop, use an if block to check and print subsets.

Example

The following Java program illustrates how to find all subsets of a String using nested for loop.

public class Demo {
   public static void main(String[] args) {
      String input_string  = "run";
      int string_length  = input_string.length();
	  // total number of subset 2^n
      int maxLen = 1 << string_length ;
      System.out.println("Given String: " + input_string);
      System.out.print("Subsets of the String: ");
	  // creating substrings 
      for (int i = 0; i < maxLen; i++) {
         String string_subset = "";
         for (int j = 0; j < string_length ; j++) {
            if ((i & (1 << j)) > 0) {
               string_subset += input_string.charAt(j);
            }
         }
         System.out.println(string_subset);
      }
   }
}

On executing, this code will display below result ?

Given String: run
Subsets of the String: 
r
u
ru
n
rn
un
run

Using substring() Method

The substring() method of Java String class is used to retrieve subsets of the specified string. This method accepts two parameters which are the start index and end index and prints the subsets in this range.

Example

In this example, we are using substring() method to print all the subsets of the given string.

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

When you run the code, following output will be displayed ?

The string is defined as: JVM
The subsets of the string are:
J
JV
JVM
V
VM
M
Updated on: 2024-08-01T10:58:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements