Find all substring in a string in C#

 Find all substrings in a string in C#

In this article, we will see c# programming to find all substrings in a given string.

below is the programme

private static void FindAllSubstring()

{

  Console.Write("Enter a String : ");

  string inputString = Console.ReadLine();

  Console.WriteLine("All substrings for given string are : ");

  for (int length = 1; length < inputString.Length; length++)
  {

    Dictionary < int, string > compare = new Dictionary<int, string>();

  int k = 0;

    for (int index = 0; index <= inputString.Length - length; index++)
    {

   string subString = inputString.Substring(index, length);

      if (!compare.ContainsValue(subString)) {

        compare.Add(k, subString);

        k++;

        Console.WriteLine(subString);

      }

    }

  }

}


In this program, we are using a dictionary, and the reason for that is, if a string contains the same character more than once, it will print one time only, we are comparing if a substring already exists then dont print that.

below is the output



Using LINQ to Find All and Unique Substrings of a Given String in C#:

private static void FindAllSubstring()

{

  Console.Write("Enter a String : ");

    string inputString = Console.ReadLine();



  var Substrings =

    from i in Enumerable.Range(0, inputString.Length)

  from j in Enumerable.Range(0, inputString.Length - i + 1)

   where j >= 1

   select inputString.Substring(i, j);



  Console.WriteLine();

  Console.WriteLine("All substrings for given string are : ");

  foreach(string substring in Substrings)

  {

    Console.WriteLine(substring);

  }

  Console.WriteLine();

  Console.WriteLine();

  Console.WriteLine("All Unique substrings for given string are : ");

  foreach(string substring in Substrings.Distinct())

  {

    Console.WriteLine(substring);

  }

}
In the above program to get the unique substring we are using distinct keywords.

Find below output


Another way to do it is below

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string input = "abcd";
        List<string> substrings = GetAllSubstrings(input);
       
        Console.WriteLine("All Substrings:");
        foreach (var substring in substrings)
        {
            Console.WriteLine(substring);
        }
    }

    static List<string> GetAllSubstrings(string str)
    {
        List<string> substrings = new List<string>();

        for (int i = 0; i < str.Length; i++)
        {
            for (int len = 1; len <= str.Length - i; len++)
            {
                substrings.Add(str.Substring(i, len));
            }
        }

        return substrings;
    }
}




Share this

Related Posts

Previous
Next Post »