public static void main(String[] args) {
String haystack = "aaaaasdfasof";
String needle = "df";
char[] hs = haystack.toCharArray();
int hl = hs.length;
char[] ns = needle.toCharArray();
int nl = ns.length;
//haystack是空字符串时needle是空返回0否则-1
if (0 >= hl) {
System.out.print(nl == 0 ? hl : -1);
}
if (nl == 0) {
System.out.print(0);
}
//第一个值
char first = ns[0];
//长度差
int max = hl - nl;
//循环长度差值次数
for (int i = 0; i <= max; i++) {
//不是第一个值
if (hs[i] != first) {
//循环到第一个对比值相等的值的位置
while (++i <= max && hs[i] != first);
}
//未到最大值
if (i <= max) {
//对比值的下一个值
int j = i + 1;
//对比值的最后一个值
int end = j + nl - 1;
//从下一个值开始判断每个值是否和要对比的值相等直到要对比的最后一个值
for (int k = 1; j < end && hs[j] == ns[k]; j++, k++);
if (j == end) {
System.out.print(i);
}
}
}
System.out.print(-1);
}