C# program to Find all substring in a string
Here's a C# program that finds all substrings in a given string:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string inputString = "abc";
List substrings = FindAllSubstrings(inputString);
Console.WriteLine("Substrings found:");
foreach (string substring in substrings)
{
Console.WriteLine(substring);
}
}
static List FindAllSubstrings(string inputString)
{
List substrings = new List();
// Iterate over each character in the string
for (int i = 0; i < inputString.Length; i++)
{
// Generate substrings starting from the current character
for (int j = i; j < inputString.Length; j++)
{
string substring = inputString.Substring(i, j - i + 1);
substrings.Add(substring);
}
}
return substrings;
}
}
In this program, we have the FindAllSubstrings method that takes a string as input and returns a list of all substrings found in the string.
We initialize an empty List named substrings to store the substrings.
We use two nested loops to generate the substrings. The outer loop iterates over each character in the string, starting from the first character. The inner loop generates substrings starting from the current character. It iterates from the current character index to the end of the string.
Inside the inner loop, we use the Substring method to extract the substring from the current character index i to the current inner loop index j. We add each substring to the substrings list.
Finally, we return the substrings list containing all the found substrings.
In the example above, the output would be:
Substrings found:
a
ab
abc
b
bc
c
All the possible substrings of the input string "abc" are found and displayed.