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.
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:
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.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework