Home  >  Article  >  Backend Development  >  C# program to find all substrings in a string

C# program to find all substrings in a string

WBOY
WBOYforward
2023-09-09 18:57:02820browse

C# 程序查找字符串中的所有子字符串

Find all substrings in a string using the substring() method in C#.

Suppose our string is -

Xyz

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);
}

Example

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

Live Demo

using System;
class Demo {
   static void Main() {
      string str = "xyz";
      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

x
y
z
xy
yz

The above is the detailed content of C# program to find all substrings in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete