Java get all substrings

Java get all substrings

  • Searching For Characters and Substring in a String in Java
  • Program to reverse a string (Iterative and Recursive)
  • Left Rotation and Right Rotation of a String
  • Sort string of characters
  • Print the frequency of each character in Alphabetical order
  • Swap characters in a String
  • C program to find the length of a string
  • How to insert characters in a string at a certain position?
  • Program to check if two strings are same or not
  • Concatenating Two Strings in C
  • Remove all occurrences of a character in a string
  • Program to print all substrings of a given string
  • Print all subsequences of a string
  • Count Distinct Subsequences
  • Count distinct occurrences as a subsequence
  • Longest Common Subsequence (LCS)
  • Shortest Superstring Problem
  • Printing Shortest Common Supersequence
  • Shortest Common Supersequence
  • Longest Repeating Subsequence
  • Longest Palindromic Subsequence (LPS)
  • Longest Palindromic Substring
  • K’th Non-repeating Character
  • Queries for characters in a repeated string
  • URLify a given string (Replace spaces with %20)
  • Count of total anagram substrings
  • Count number of binary strings without consecutive 1’s
  • Lexicographically next string
  • Check if given string can be split into four distinct strings
  • Word Break Problem | (Trie solution)
  • Check for balanced parentheses in an expression | O(1) space
  • Length of Longest Balanced Subsequence
  • Minimum Swaps for Bracket Balancing
  • Convert a sentence into its equivalent mobile numeric keypad sequence
  • Burrows – Wheeler Data Transform Algorithm
  • Form minimum number from given sequence
  • Print shortest path to print a string on screen
  • Mirror characters of a string
  • Multiply Large Numbers represented as Strings
  • Count ways to increase LCS length of two strings by one
  • Minimum rotations required to get the same string
  • Find if an array of strings can be chained to form a circle | Set 2
  • Given a sorted dictionary of an alien language, find order of characters
  • Remove minimum number of characters so that two strings become anagram
  • Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
  • Palindrome Substring Queries
  • Minimum Word Break
  • Minimum number of bracket reversals needed to make an expression balanced
  • Word Wrap problem ( Space optimized solution )
  • Decode a string recursively encoded as count followed by substring
  • Searching For Characters and Substring in a String in Java
  • Program to reverse a string (Iterative and Recursive)
  • Left Rotation and Right Rotation of a String
  • Sort string of characters
  • Print the frequency of each character in Alphabetical order
  • Swap characters in a String
  • C program to find the length of a string
  • How to insert characters in a string at a certain position?
  • Program to check if two strings are same or not
  • Concatenating Two Strings in C
  • Remove all occurrences of a character in a string
  • Program to print all substrings of a given string
  • Print all subsequences of a string
  • Count Distinct Subsequences
  • Count distinct occurrences as a subsequence
  • Longest Common Subsequence (LCS)
  • Shortest Superstring Problem
  • Printing Shortest Common Supersequence
  • Shortest Common Supersequence
  • Longest Repeating Subsequence
  • Longest Palindromic Subsequence (LPS)
  • Longest Palindromic Substring
  • K’th Non-repeating Character
  • Queries for characters in a repeated string
  • URLify a given string (Replace spaces with %20)
  • Count of total anagram substrings
  • Count number of binary strings without consecutive 1’s
  • Lexicographically next string
  • Check if given string can be split into four distinct strings
  • Word Break Problem | (Trie solution)
  • Check for balanced parentheses in an expression | O(1) space
  • Length of Longest Balanced Subsequence
  • Minimum Swaps for Bracket Balancing
  • Convert a sentence into its equivalent mobile numeric keypad sequence
  • Burrows – Wheeler Data Transform Algorithm
  • Form minimum number from given sequence
  • Print shortest path to print a string on screen
  • Mirror characters of a string
  • Multiply Large Numbers represented as Strings
  • Count ways to increase LCS length of two strings by one
  • Minimum rotations required to get the same string
  • Find if an array of strings can be chained to form a circle | Set 2
  • Given a sorted dictionary of an alien language, find order of characters
  • Remove minimum number of characters so that two strings become anagram
  • Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
  • Palindrome Substring Queries
  • Minimum Word Break
  • Minimum number of bracket reversals needed to make an expression balanced
  • Word Wrap problem ( Space optimized solution )
  • Decode a string recursively encoded as count followed by substring
Читайте также:  Script type javascript template

Источник

How to find all substrings of a string in Java

In this short article, we are going to showcase how to find all substrings of a string in Java.

First, we will start by showing how to do this using core Java methods. Then, we are going to highlight how to achieve the same thing using external libraries.

Java provides several methods and classes to print all possible substrings of a given string. So, let’s take a close at each approach.

Using String.substring() Method

substring() offers the easiest way to get substrings from an original string.

So, let’s illustrate how we can use it using a practical example:

 String str = "Hello"; ListString> substringList = new ArrayListString>(); for (int i = 0; i for (int j = i + 1; j > System.out.println(substringList); 

using substring method

As we can see, we used two loops. Since the substring() method has a time complexity of o(n), the above approach has a o(n^3) time complexity.

Using StringBuffer Class

Similarly, we can use the StringBuffer class to extract all the substrings. However, the time complexity will jump to O(n)2.

So, let’s exemplify the use of the StringBuffer class:

 String str = "foo"; int length = str.length(); char[] strChars = str.toCharArray(); ListString> substringList = new ArrayListString>(); int i = 0; while (i < length) < StringBuffer buildStr = new StringBuffer(); buildStr.append(strChars[i]); for (int j = i + 1; j if (j < length) < buildStr.append(strChars[j]); >> i++; > System.out.println(substringList); 

The program will produce the output:

We used the toCharArray() method to convert a string into a char[] array. Then, we used the StringBuffer class to build all the possible portions.

Alternatively, another solution would be using the StringBuilder class. The only difference is that StringBuilder is not thread-safe.

Using Apache Commons Lang Library

This external library comes with a set of ready-to-use utility classes. Among these classes, we find the StringUtils.

As the name indicates, it’s a utility class that provides a convenient way to operate on strings in a null-safe manner.

 String str = "bar"; int strLength = StringUtils.length(str); for (int i = 0; i for (int j = i + 1; j .out.println(StringUtils.substring(str, i, j)); > > 

As shown above, we used StringUtils.length() to get the length of the original string.

Then, we used the StringUtils.substring() method to find all the possible substrings.

Find all Unique Substrings

Now, let’s see how to print all the possible unique subregions of a particular string.

Typically, we can use a HashSet implementation to achieve this. By design, HashSet does not accept duplicate values:

 import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class UniqSubstrings < public UniqSubstrings() < >public static void main(String[] args) < String str = "deev"; SetString> uniqSubs = new HashSetString>(); for (int i = 0; i for (int j = i + 1; j > IteratorString> siterator = uniqSubs.iterator(); while(siterator.hasNext())< System.out.println(siterator.next()); > > > 

The above program will output:

 ee de ev d dee e v eev deev 

Conclusion:

To sum it up, we have showcased how to find all substrings of a string in Java.

Along the way, we illustrated how to do this using built-in Java methods and classes.

Then, we explained how to accomplish the same objective using Apache Commons library.

Liked the Article? Share it on Social media!

If you enjoy reading my articles, buy me a coffee ☕. I would be very grateful if you could consider my request ✌️

Источник

Find all substrings of a String in java

Above solution is of o(n^3) time complexity. As we have two loops and also String’s substring method has a time complexity of o(n)
If you want to find all distinct substrings of String,then use HashSet to remove duplicates.

Please go through Frequently asked java interview Programs for more such programs.

Was this post helpful?

You may also like:

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor

Convert LocalDate to Instant in Java

Convert Instant to LocalDate in Java

Convert String to LocalDateTime in Java

Format LocalDateTime to String in Java

Java 8 – Find duplicate elements in Stream

How to format Instant to String in java

Java Date to LocalDate

Java LocalDate to Date

Java Stream to List

Share this

Author

Star pattern in java

Star Pattern programs in Java

Convert Roman number to Integer in java

Convert Roman Number to Integer in Java

Rock Paper Scissors Game in Java

Find automorphic number in java

Find nth prime number in java

Implement distance formula in java

In this post, we will see how to implement distance formula between two points in java. Formula to find distance between two points ( x1, y1) and (x2 , y2) is d= sqrt( (x2-x1)^2+ (y2 – y1)^2) Here is simple program to calculate distance between two points in java. [crayon-64b80af3c9853124614862/] Here we have used math.sqrt […]

Источник

Java Program – Find all Possible Substrings of a String

To find all substrings of a string, use a nested loop, where one of the loop traverses from one end of the string other, while the other loop changes the length of substring.

In this tutorial, we shall write Java programs to find all possible substrings of a string, and also to find all unique substrings of a string.

All Substrings of a String using Nested For Loop

Algorithm

We shall use following algorithm to find the substrings of a string.

  1. Start.
  2. Read string to str .
  3. Take an empty list allSubstrings to store all the substrings.
  4. Initialize len with 1 .
  5. Check if len is less than or equal to string str length. If false, go to step 11.
  6. Initialize index with 0 .
  7. Check if index is less than or equal to the difference of string str length and len . If false go to step 10.
  8. Add the substring of str , with start as index and end as index+len , to allSubstrings .
  9. Increment index. Go to step 7.
  10. Increment len. Go to step 5.
  11. allSubstrings has all the substrings. You may print them.
  12. Stop.

Example.java

import java.util.List; import java.util.ArrayList; import java.util.Arrays; /** * Java Program - All Substrings */ public class Example < public static void main(String[] args) < String str = "apple"; ListallSubstrings = new ArrayList(); for(int len=1; len > System.out.println(Arrays.toString(allSubstrings.toArray())); > >
[a, p, p, l, e, ap, pp, pl, le, app, ppl, ple, appl, pple, apple]

All Unique Substrings of a String

To store only unique substrings, instead of a Java List, use Java HashSet to store the substrings in the nested loop.

Example.java

import java.util.Arrays; import java.util.HashSet; /** * Java Program - All Substrings */ public class Example < public static void main(String[] args) < String str = "apple"; HashSetallSubstrings = new HashSet(); for(int len=1; len > System.out.println(Arrays.toString(allSubstrings.toArray())); > >
[a, p, p, l, e, ap, pp, pl, le, app, ppl, ple, appl, pple, apple]

Conclusion

In this Java Tutorial, we learned how to find all substrings of a given string, with the help of Java programs.

Источник

Оцените статью