Write a C# program to find the number of times a substring appears in the given string

Introduction

I have use Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability..

using System;
public class stringexercise
{
    public static void Main()
    {
        string str;
        string findstring;
        int start = 0;
        int cnt = -1;
        int index = -1;
 
        Console.Write("Input the original string : ");
        str = Console.ReadLine();
        Console.Write("Input the string to be searched for : ");
        findstring = Console.ReadLine();
 
        while (start != -1)
        {
            start = str.IndexOf(findstring, index + 1);
            cnt += 1;
            index = start;
        }
        Console.Write("The string '{0}' occurs " + cnt + " times.\n", findstring);
 
        Console.ReadLine();
    }
}

Result

Write a C# program to find the number of times a substring appears in the given string
Write a C# program to find the number of times a substring appears in the given string

Leave a Comment