The c string finds the number of times a word appears and its index

  • 2020-06-12 10:30:52
  • OfStack

Use of string methods:

indexof () :

There are 9 overloads, please go to F12 for details.

This article USES the sixth overload:

If the string is found, the zero-based index position; If the string is not found, it is -1

There are two parameters:

string value: The characters to search for

int startIndex: The starting location of the search


class Program
    {
        static void Main(string[] args)
        {
            // Count the occurrence times of snow in the string, and the index position of each occurrence; 
            string text = " Did it snow today? Will it not snow tomorrow? When will it not snow? ";
            string keyWord = " It snows ";
            int index = 0;
            int count = 0;
            while ((index=text.IndexOf(keyWord,index))!=-1)
            {
                count++;
                Console.WriteLine(" The first {0} Times; The index is {1}",count,index);
                index =index+ keyWord.Length;
            }
            Console.WriteLine(" Total number of snow occurrences: {0}",count);
            Console.ReadKey();
        }
    }


Related articles: