This is the second solution to list all the subsets or substrings of a given string. This program does not use the substring method, instead uses the StringBuilder class append method.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class SubstringsWithoutUsingMethod {
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> finalSubsetStrs = new HashSet<String> ();
Scanner inpStr=new Scanner (System.in);
System.out.println("Enter an input word for which you need all the sub sets of strings");
String inpWord=inpStr.next();
int sizeOfSubstr=1,beginIdx=0, endIdx=1;
//Iterate the loop until the substring's length is equals with length of the actual string
while (sizeOfSubstr <= inpWord.length()) {
//Iterate the substring sized loop until the subscript less than or equals the actual length
while (beginIdx < inpWord.length() && endIdx <= inpWord.length())
finalSubsetStrs.add(prepSubstr(beginIdx++, endIdx++,inpWord));
sizeOfSubstr++; // Increment size of sub string for the next iteration
beginIdx=0;
endIdx=sizeOfSubstr;
}
System.out.println("All the unique substrings from the given String="+inpWord+" are below");
System.out.println(finalSubsetStrs);
inpStr.close();
}
//Function to form the subStrings using StringBuilder Mutable class object
private static String prepSubstr(int bIdx, int eIdx, String inpWord) {
StringBuilder formStr=new StringBuilder ();
for(int i=bIdx;i<=eIdx-1;i++ )
formStr.append(inpWord.charAt(i));
return formStr.toString();
}
}
OUTPUT
Enter an input word for which you need all the sub sets of strings
AAAAB
All the unique substrings from the given String=AAAAB are below
[AA, AAAAB, A, AB, AAA, B, AAB, AAAA, AAAB]

Leave a comment