Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Find the number of times a substring appears in a string

C# Sharp String: Exercise-19 with Solution

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

C# Sharp Exercises: Find the number of times a substring appears in a string.

Sample Solution:-

C# Sharp Code:

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

Sample Output:

Find the number of times a specific string appears in a string :       
--------------------------------------------------------------------   
Input the original string : Welcome to w3resource.com                  
Input the string to be searched for : w3resource                       
The string 'w3resource' occurs 1 times.

Flowchart:

Flowchart: Find the number of times a substring appears in a string

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to check whether a character is an alphabet and not and if so, go to check for the case.
Next: Write a program in C# Sharp to insert a substring before the first occurrence of a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.