create a search word method to scan a paragraph of text with a denounce in csharp

To create a search word method to scan a paragraph of text with denounce in C#, you can use the string.IndexOf() method combined with a loop to match the search word and avoid false positives.

Here's a sample code to achieve this:

main.cs
public bool SearchWord(string text, string searchWord, int denounce)
{
    int index = 0;
    int count = 0;

    while ((index = text.IndexOf(searchWord, index, StringComparison.OrdinalIgnoreCase)) != -1)
    {
        count++;

        if (count == denounce)
        {
            return true;
        }

        index += searchWord.Length;
    }

    return false;
}
370 chars
20 lines

This method takes in three parameters:

  • text which is the paragraph of text to be searched
  • searchWord which is the word to be searched for
  • denounce which is the number of times the search word should appear in the text for the method to return true

The method uses IndexOf() method to find the first occurrence of the search word in the text. It then uses a loop to keep searching for the search word in the remaining text until the specified denounce is reached.

Note that we are using StringComparison.OrdinalIgnoreCase to make the search case-insensitive.

Finally, if the search word appears the specified number of times in the text, the method returns true. Otherwise, it returns false.

related categories

gistlibby LogSnag