# C#LeetCode刷题之#28-实现strStr()（Implement strStr()）

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Input: haystack = “hello”, needle = “ll”

Output: 2

Input: haystack = “aaaaa”, needle = “bba”

Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

```public class Program {

public static void Main(string[] args) {
var haystack = "hello";
var needle = "ll";

var res = StrStr(haystack, needle);
Console.WriteLine(res);

haystack = "mississippi";
needle = "issipi";

res = StrStr2(haystack, needle);
Console.WriteLine(res);

}

private static int StrStr(string haystack, string needle) {
//利用运行库，无耻的解法
return haystack.IndexOf(needle);
}

private static int StrStr2(string haystack, string needle) {
//定义匹配变量
var match = true;
//从首字母循环，后面的部分无需放在外循环
//因为内循环可以比较到
for(var i = 0; i <= haystack.Length - needle.Length; i++) {
//默认为匹配
match = true;
for(var j = 0; j < needle.Length; j++) {
//使用内循环逐一判定是否每个字母都能匹配
if(haystack[i + j] != needle[j]) {
//发现不匹配时立刻退出内循环
match = false;
break;
}
}
//如果全部匹配，则直接返回i
if(match) return i;
}
//无法完成匹配
return -1;
}

}```

```2
-1```

(1)