How to List all Substrings in a given String using C#?


To list all the substrings, use the Substring method and loop through the length of the string.

Let’s say our string is −

string myStr = "pqrz";

Use nested loop and get the substring in a new string −

for (int i = 1; i < myStr.Length; i++) {
   for (int start = 0; start <= myStr.Length - i; start++) {
      // get substrings
   }
}

The following is the complete code −

Example

using System;

public class Demo {
   public static void Main() {
      string myStr = "pqrz";

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

Updated on: 22-Jun-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements