Leetcode / 28. Find the Index of the First Occurrence in a String
Pick a programming language:
Here is the source code for the solution to this problem.
public class Solution {
public int StrStr(string haystack, string needle) {
for (int i = 0; i <= haystack.Length - needle.Length; i++)
{
bool matches = true;
for (int j = 0; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
{
matches = false;
break;
}
}
if (matches)
{
return i;
}
}
return -1;
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: