Tutorialspoint
Problem
Solution
Submissions

Substrings of a String

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a C# program to find and print all possible substrings of a given string. A substring is a contiguous sequence of characters within a string. For example, the substrings of "abc" are "a", "b", "c", "ab", "bc", and "abc".

Implement the FindAllSubstrings(string str) function which:

  1. Takes a string as input
  2. Returns a list or array containing all possible substrings of the input string
  3. The substrings should be returned in order of increasing length and from left to right
Example 1
  • Input: str = "abc"
  • Output: ["a", "b", "c", "ab", "bc", "abc"]
  • Explanation:
    • Substrings of length 1: "a", "b", "c"
    • Substrings of length 2: "ab", "bc"
    • Substrings of length 3: "abc"
Example 2
  • Input: str = "xy"
  • Output: ["x", "y", "xy"]
  • Explanation:
    • Substrings of length 1: "x", "y"
    • Substrings of length 2: "xy"
Constraints
  • 1 <= str.length <= 100
  • str consists of lowercase and uppercase English letters
  • Time Complexity: O(n²)
  • Space Complexity: O(n²) where n is the length of the string
StringsControl StructuresPwCSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to generate all possible substrings
  • The outer loop defines the starting position of the substring
  • The inner loop defines the ending position of the substring
  • Use string.Substring() method to extract the substring
  • Add each substring to a list to return all of them

Steps to solve by this approach:

 Step 1: Create an empty list to store all substrings
 Step 2: Check if the input string is null or empty
 Step 3: Use an outer loop to iterate through all possible substring lengths (from 1 to string length)
 Step 4: Use an inner loop to iterate through all possible starting positions for each length
 Step 5: Extract the substring using the Substring method and add it to the result list
 Step 6: Return the list containing all substrings

Submitted Code :