3.13 第28题 实现strStr()
题目
实现strStr()函数。
给定一个haystack字符串和一个needle 字符串,在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1。
解答
使用indexOf()函数。
public class Solution28 {
public static int strStr(String haystack, String needle){
return haystack.indexOf(needle);
}
public static void main(String[] args){
int index = strStr("hello","ll");
System.out.println(index);
}
}
知识点
-
记住一定要思考有没有现成的函数可以调用实现此功能。
-
还是indexOf()函数的使用
-
public int indexOf(int ch):返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。
-
public int indexOf(int ch,int fromIndex);返回从fromIndex位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回-1。
-