Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

How to find the starting index of all occurrences of a word in a string in C#

1 Answer

0 votes
using System;

class FindOccurrences
{
    /*
        Find all starting indices of a word inside a larger text.
        This function uses String.IndexOf in a loop. The method is efficient
        and implemented in optimized native code, making it ideal for substring search.
    */
    static void FindAllOccurrences(string text, string word)
    {
        if (string.IsNullOrEmpty(word)) {
            return; // Searching for an empty word is meaningless
        }

        int index = text.IndexOf(word); // First occurrence

        while (index != -1) {
            Console.WriteLine(index);   // Print the index

            /*
                Search again starting one character after the previous match.
                This allows detection of overlapping matches.
            */
            index = text.IndexOf(word, index + 1);
        }
    }

    static void Main()
    {
        string text =
            "the quick brown fox jumps over the lazy dog. the fox is clever.";
        string word = "the";

        Console.WriteLine("Text: " + text);
        Console.WriteLine("Word: \"" + word + "\"");
        Console.WriteLine();
        Console.WriteLine("Occurrences at indices:");

        FindAllOccurrences(text, word);
    }
}


/*
run:

Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"

Occurrences at indices:
0
31
45

*/

 



answered Aug 30 by avibootz

Related questions

...