给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中
* 找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
* 当 needle 是空字符串时我们应当返回 0 。
package com.henu;
/**
* @author limengdong
* @description:给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中
* 找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
* 当 needle 是空字符串时我们应当返回 0 。
*/
public class Demo07 {
public static void main(String[] args) {
String hayStack = "helohello";
String needle = "ello";
//定义一个pl,相当于一个flag
int pl = 0;
//定义一个index,对于最后的取值
int index = 0;
for (int i = 0; i < hayStack.length(); i++) {
index = i;//此时的i为needle在hayStack中
String str = "";
for (int j = i; str.length() < needle.length(); j--) {
if (j >= 0) {
str = hayStack.charAt(j) + str;
}else {
break;
}
}
if (needle.equals(str)) {
pl = 1;
break;
}else {
pl = 0;
}
}
if (needle == "") {
System.out.println("0");
}else if (pl == 1) {
System.out.println(index+1-needle.length());
}else {
System.out.println(-1);
}
}
}