using System;
class program {
public static void Main() {
string s1;
Console.WriteLine("Enter the String : ");
s1 = Console.ReadLine();
Console.WriteLine(counting.CountStringOccurrences(s1, "the"));
Console.ReadLine();
}
}
public static class counting {
public static int CountStringOccurrences(string text, string pattern) {
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1) {
i += pattern.Length; count++;
}
return count;
}
}
Here is the output of the C# Program:
Enter the String :
Please find the all the examples in this blog and achieve success in your interviews.
2
class program {
public static void Main() {
string s1;
Console.WriteLine("Enter the String : ");
s1 = Console.ReadLine();
Console.WriteLine(counting.CountStringOccurrences(s1, "the"));
Console.ReadLine();
}
}
public static class counting {
public static int CountStringOccurrences(string text, string pattern) {
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1) {
i += pattern.Length; count++;
}
return count;
}
}
Here is the output of the C# Program:
Enter the String :
Please find the all the examples in this blog and achieve success in your interviews.
2
Hi Mallikarjun can you check this below,
ReplyDeletewhile ((i = text.IndexOf(pattern, i)) != -1) {
i += pattern.Length; count++;
}
if the inputs are same(as you given)
First check i value is 36(bcz its checking the 0th index) then it will go inside and do the logic (Now i value is 40).
again check the while condition, this time we are seaching for the indexed 40th position which is not available in the string so it will cause to raise argumentout of range exception.
So please check if am wrong.
Rather you can try keep int temp=text.IndexOf(pattern, 0);
Deletethen
while(temp!=-1)
{
temp = text.IndexOf(pattern, temp + pattern.Length);
count++;
}
return count;
Hi venk120 Soft,thank you for visiting my blog and reading my article
ReplyDeleteu r snippet is also worked fine for above solution of given input string "Please find the all the examples in this blog and achieve success in your interviews." i think it doesn't reduce the no.of times looping
from the above snippet u r passing the position of next matched string,instead of first occurrence of string+length.
so,it also one way to solve the output.
Thank You..