Find all substrings in a string using C#


Use the substring() method in C# to find all substrings in a string.

Let’s say our string is −

pqr

Loop through the length of the string and use the Substring function from the beginning to the end of the string −

for (int start = 0; start <= str.Length - i; start++) {
   string substr = str.Substring(start, i);
   Console.WriteLine(substr);
}

The following is the C# program to find all substrings in a string −

Example

 Live Demo

using System;

class Demo {
   static void Main() {
      string str = "pqr";

      for (int i = 1; i < str.Length; i++) {
         for (int start = 0; start <= str.Length - i; start++) {
            string substr = str.Substring(start, i);
            Console.WriteLine(substr);
         }
      }
   }
}

Output

p
q
r
pq
qr

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements