用于估计句子中单词“is”出现频率的 C# 程序
给定一个字符串作为输入,我们需要用 C# 编写一个程序来计算字符串中单词“is”出现的频率。程序的任务是计算给定单词“is”在字符串中出现的次数,并打印“is”出现的次数。
例子:
Input : string = “The most simple way to prepare for interview is to practice on best computer science portal that is GeeksforGeeks”
Output : Occurrences of “is” = 2 Time
Input : string = “is this is the way to talk to your sister? I don’t know what that is”
Output : Occurrences of “is” = 3 Time
Explanation: The “is” has also occurred in the word “sister” and “this” but we are looking for the word “is” to occur separately. Hence only 3 time.
使用迭代方法
方法:
- Split the string by spaces
- Store all the words in an array of strings.
- Now run a loop at 0 to the length of the array of string and check if our string is equal to the word “is”.
- If the condition is true increment the count else do not increment it.
代码:
C#
// C# program to count the number
// of occurrence of a "is" in
// the given string
using System;
class GFG{
static int countOccurrencesOfIs(string str)
{
// Split the string by spaces
string[] a = str.Split(' ');
string word = "is";
// Search for "is" in string
int count = 0;
for(int i = 0; i < a.Length; i++)
{
// If "is" found increase count
if (word.Equals(a[i]))
count++;
}
return count;
}
// Driver code
public static void Main()
{
string str = "is this is the way to talk to your " +
"sister? I don't know what that is";
Console.Write(countOccurrencesOfIs(str));
}
}
输出:
3
时间复杂度: O(n) 其中 n 是字符串的长度。