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

CsharpProgrammingServer Side Programming

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);
         }
      }
   }
}
raja
Published on 31-Aug-2018 09:20:45
Advertisements