Q:

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

0

Write a program in C# Sharp to find the number of times a substring appears in a given string. 
Test Data :
Input the original string : this is original string
Input the string to be searched for : str
Expected Output :

The string 'str' occurs 1 times

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

using System;
public class exercise19
{
	public static void Main()
	{
	 string str1;
	 string findstring;
     int strt = 0;
     int cnt = -1;
     int idx = -1;
       Console.Write("\n\nFind the number of times a specific string appears in a string :\n");
       Console.Write("--------------------------------------------------------------------\n");	
	Console.Write("Input the original string : ");
       str1 = Console.ReadLine();
	Console.Write("Input the string to be searched for : ");
       findstring = Console.ReadLine();       	   
    while (strt != -1)
     {
         strt = str1.IndexOf(findstring, idx + 1);
         cnt += 1;
         idx = strt;
     }
     Console.Write("The string '{0}' occurs " + cnt + " times.\n", findstring);	   
	}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now