programming-examples/c-sharp/Strings/C# Sharp to find the number of times a substring appears in the given string.cs

25 lines
861 B
C#
Raw Normal View History

2019-11-15 12:59:38 +01:00
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);
}
}