用于将set / Converting String的所有子集打印到char []

时间:2018-06-10 10:38:27

标签: java recursion subset

我想找到一组递归的所有子集,这里是我的代码。我的问题在于这一部分:

char[] set = in.nextLine().toCharArray().split("(?!^)");

当我运行此代码时,我收到此错误,我不知道如何解决它。

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot invoke split(String) on the array type char[]

at subsetGeek.Main.main(Main.java:35)

我想从用户那里获取带有这部分代码的Set,将它放入char []然后显示子集。

// A Java program to print all subsets of a set
    import java.io.IOException;
    import java.util.Scanner;
    class Main
    {
        // Print all subsets of given set[]
        static void printSubsets(char set[])
        {
            int n = set.length;

        // Run a loop for printing all 2^n
        // subsets one by obe
        for (int i = 0; i < (1<<n); i++)
        {
            System.out.print("{ ");

            // Print current subset
            for (int j = 0; j < n; j++)

                // (1<<j) is a number with jth bit 1
                // so when we 'and' them with the
                // subset number we get which numbers
                // are present in the subset and which
                // are not
                if ((i & (1 << j)) > 0)
                    System.out.print(set[j] + " ");

            System.out.println("}");
        }
    }

    // Driver code
    public static void main(String[] args)
    {   Scanner in = new Scanner(System.in);
        char[] set = in.nextLine().toCharArray().split("(?!^)");
        //char set[] = {'a', 'b', 'c'};
        printSubsets(set);
    }
}

还有什么可以替换我的代码的那部分吗?

1 个答案:

答案 0 :(得分:0)

用以下代码替换您的错误代码行。

char[] set = in.nextLine().replaceAll("[?!^]","").toCharArray();