给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
- 方法一:将字符串先转换为字符数组
public class Strstr {
public static void main(String[] args) {
String haystack = "walllo";
String needle = "lo";
System.out.println(strFirst(haystack, needle));
}
private static int strFirst(String haystack, String needle) {
if(needle.length()==0){
return 0;
}
int h = haystack.length();
int n = needle.length();
char[] chars = haystack.toCharArray();
char[] chars1 = needle.toCharArray();
for(int i=0;i<=h-n;i++){
//定义中间变量
int a = i;
int j = 0;
while(j<n && chars[a]==chars1[j]){
a++;
j++;
}
if(j==n){
return i;
}
}
return -1;
}
}
- 方法二:字符比较
public class Strstr {
public static void main(String[] args) {
String haystack = "walllo";
String needle = "lo";
System.out.println(strFirst(haystack, needle));
}
private static int strFirst(String haystack, String needle) {
if(needle.length()==0){
return 0;
}
int h = haystack.length();
int n = needle.length();
for(int i=0;i<=h-n;i++){
int j = 0;
while(j<n){
if(haystack.charAt(i+j)!=needle.charAt(j)){
break;
}
j++;
}
if(j==n) return i;
}
return -1;
}
}