DEV Community

Rathod Ketan
Rathod Ketan

Posted on • Originally published at interviewspreparation.com

How To Find The First Occurrence of a string

Welcome back, visitors. In this post, I will delve into the concepts of 'what is string occurrence' and 'Find The First Occurrence Index.' These are frequently posed by interviewers when seeking candidates for junior or internship positions.

'Find the index of the first occurrence in a string' or 'How to find all occurrences of a substring' are also topics covered on LeetCode and GeeksforGeeks websites. To master solving these problems, continue following the guidance on this page until the end, and you will gain expertise in find the occurrence of a substring in a string.

If you're a new visitor, this message is for you. If you're gearing up for a programmer role interview and require assistance, consider joining our Quora community group. It's free and provides a platform where you can pose questions and receive answers within 24 hours. Additionally, if you're interested in tackling beginner and intermediate level programming challenges, be sure to follow our dedicated pages for that purpose.

What Is String Occurrence ?

When an interviewer poses this question, your response should clarify that the occurrence of a string refers to how many times a particular string repeats within another string. In simpler terms, the number of times a substring appears in a string is referred to as string occurrence.

Allow me to provide a practical example to illustrate the occurrence of a substring or string. Consider the string 'interviewspreparation.com,' which represents my website. In this case, 'interview' is the substring we are interested in locating within the entire string 'interviewspreparation.com.' The task involves finding how many times the term 'interview' appears within the string.

And our answer would be 1 time in 0 index of the string. understood find the first occurrence of substring?

Program To Find The First Occurrence In A String

Want to understand steps how does it working ? do follow us

static int GetTheIndexOfTheFirstOccurrence(string haystack, string needle)
{

    for (int i = 0; i < haystack.Length; i++)
    {
        string temp = "";

        for (int j = i; j < haystack.Length && j <= i + needle.Length - 1; j++)
        {
            temp += haystack[j];
        }

        Console.WriteLine(temp);

        if (temp == needle)
        {
            return i;
        }
    }

    return -1;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)