C# Program to Find All Substrings in a String

«
»

This is a C# Program to list all substrings in a given string.

Problem Description

This C# Program Lists all Substrings in a given String.

Problem Solution

Here Substring function extracts strings. It requires that you indicate a start index and a length. It then returns a completely new string with the characters in that range.

Program/Source Code

Here is source code of the C# Program to List all Substrings in a given String. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to List all Substrings in a given String
 */
using System;
namespace mismatch
{
    class Program
    {
        string value, substring;
        int j, i;
        string[] a = new string[5];
        void input()
        {
            Console.WriteLine("Enter the String : ");
            value = Console.ReadLine();
            Console.WriteLine("All Possible Substrings of the Given String are :");
            for (i = 1; i <=value.Length; i++)
            {
                for (j = 0; j <= value.Length - i; j++)
                {
                    substring = value.Substring(j, i);
                    a[j] = substring;
                    Console.WriteLine(a[j]);
                }
            }
        }
        public static void Main()
        {
            Program pg = new Program();
            pg.input();
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, we are reading the string using ‘value’ variable. Then for loop is used to count all possible substrings in the given string. Here substring function extracts strings.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement

It requires that you indicate a start index and a length. It then returns a completely new string with the characters in that range. Print the list of all substrings in a given string.

Runtime Test Cases
 
Enter the String : abab
All Possible Substrings of the Given String are :
a
b
a
b
ab
ba
ab
aba
bab
abab

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.