Java程序查找字符串的所有子集
在本文中,我们将了解如何查找字符串的所有子集。在Java中,字符串是一种数据类型,包含一个或多个字符,并用双引号(“ ”)括起来。字符串的一部分或子集称为子字符串。
示例场景
Input: string = JVM; Output: The subsets of the string are: J, JV, JVM, V, VM, M
在Java中查找字符串的所有子集
使用以下方法在Java中查找字符串的所有子集:
- 使用嵌套for循环
- 使用substring()方法
使用嵌套for循环
在这种方法中,我们使用嵌套的for循环。外部循环将运行到子集的数量,内部循环将运行到字符串长度。在内部循环中,使用if块检查并打印子集。
示例
以下Java程序演示了如何使用嵌套for循环查找字符串的所有子集。
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);
}
}
}
执行后,此代码将显示以下结果:
Given String: run Subsets of the String: r u ru n rn un run
使用substring()方法
Java字符串类的substring()方法用于检索指定字符串的子集。此方法接受两个参数,即开始索引和结束索引,并在该范围内打印子集。
示例
在这个例子中,我们使用substring()方法打印给定字符串的所有子集。
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]);
}
}
}
运行代码后,将显示以下输出:
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP