原题
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
大意
判断字符串中是否包含另一个字符串,如果包含的话则返回字符串第一次出现的地方;如果没有包含的话,则返回-1
思路
本来想双层遍历字符串,然后去比较;后来想到字符串中的一个函数substring,可以提取某个长度的子字符串
代码
if(haystack.length()==0&&needle.length()==0) return 0;
else
for(int i=0;i<haystack.length()-needle.length()+1;i++){
String item=haystack.substring(i, i+needle.length());
if(needle.equals(item))
return i;
}
return -1;