Java 程序:寻找字符串所有子集

原文:https://www.studytonight.com/java-programs/java-program-to-find-all-the-subsets-of-a-string

在本教程中,我们将学习如何打印字符串的所有子集。但是在进一步深入之前,如果你不熟悉字符串的概念,那么一定要查看 Java 中Strings的文章。

输入:输入字符串:世界

输出:输入字符串的子集为:

W

O

稀有

L

D

运筹学

RL

致死剂量

试题

回波损耗

右腿驱动

单词

奥尔德

世界

程序 1:查找字符串的所有子集

在这个程序中,我们将使用三个嵌套的 for 循环来打印字符串的所有子集。第一个 for 循环用于选择开始元素,第二个 for 循环用于选择结束元素,第三个 for 循环用于打印从开始到结束元素的选定元素。

算法

  1. 开始
  2. 声明一个字符串。
  3. 要求用户初始化字符串
  4. 将其转换为字符数组。
  5. 调用一个方法来查找字符串的所有子集。
  6. 对相同的循环使用三个。
  7. 使用第一个 for 循环选择子集的起始索引。
  8. 使用第二个 for 循环来保存子集的结束索引。
  9. 使用第三个 for 循环打印所有子集。
  10. 停下来。

下面是相同的 Java 语言代码。

//Java Program to Find all the subsets of a string
import java.util.*;
public class Main
{
    //To find all the subsets of a string
   static void subString(char str[], int n)
   {
        // To select starting point
        for (int t = 1; t <= n; t++) 
        {
            // To select ending point
            for (int i = 0; i <= n - t; i++) 
            {
                //  Print characters from selected
                // starting to end point.  
                int j = i + t - 1;
                for (int k = i; k <= j; k++) 
                {
                    System.out.print(str[k]);
                }

                System.out.println();
            }
        }
    } 
    // Driver program to test above function
    public static void main(String[] args) 
    {
        //Take input from the user
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the string is "+str1);
        String str1=sc.nextLine();
        char str[] = str1.toCharArray();
        System.out.println("All the substrings of the above string are: ");
        subString(str, str.length);
    }
}

输入字符串:代码 上述字符串的所有子字符串为: C o d e Co od de Cod ode Code

程序 2:查找字符串的所有子集

在这个程序中,我们将使用 substr()方法打印给定字符串的所有子集。str.substr(i,j)将从字符串中的索引 i 开始打印长度为 j 的子字符串。

算法

  1. 开始
  2. 声明一个字符串。
  3. 初始化它。
  4. 调用一个方法来查找输入字符串的所有子集。
  5. 将字符串和字符串长度作为参数传递。
  6. 对同一个循环使用两个。
  7. 使用第一个 for 循环选择子集的起始索引。
  8. 使用第二个 for 循环来保存子集的结束索引。
  9. 打印所有子集。
  10. 停下来。

下面是相同的 Java 语言代码。

//Java Program to Find all the subsets of a string
public class Main
{
    //To find all the subsets of a string
   static void subString(String str, int n)
   {
        for (int i = 0; i < n; i++)      //To select the starting index
        {
           for (int j = i+1; j <= n; j++)    //To select the ending index
            {
                System.out.println(str.substring(i, j));
            }
        }
    }
    // Driver program to test above function
    public static void main(String[] args) 
    {
        String str="Hello";
        System.out.println("The entered string are "+str);
        System.out.println("All the substrings of the above string is: ");
        //Call to find the all the subsets of the string
        subString(str, str.length());
    }
}

输入的字符串为 Hello 上述字符串的所有子字符串为: H He Hel Hell Hello e El ell ello l ll llo l lo o