Find all substring in a string in C#

 Find all substring in a string in C#

In this article we will see c# programming to find all substring 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 programme , we are using disctionary , and the resason for that is , if a string contain same character more than once , it will print one time only , we are comparing if substring already exist 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 above programme to get the unique substring we are using distinct keyword.

Find below output



Share this

Related Posts

Previous
Next Post »