Mid Coding

Implement strStr() — Find first occurrence of a?

substring (needle) in a string (haystack)

int StrStr(string haystack, string needle)

if (needle == "") return 0;

int n = haystack.Length, m = needle.Length;

for (int i = 0; i <= n - m; i++)

int j;

Follow on:

for (j = 0; j < m; j++)

if (haystack[i + j] != needle[j])

break;

if (j == m) return i; // found

return -1;

Explanation:

Simple sliding window check each position; returns starting index or -1.

More from C# Programming Tutorial

All questions for this course