package com.test5;
public class Test2 {
public static void main(String[] args) {
//返回子串sub在s中第一次出现的位置,如果没找到返回-1
String s ="aasaewqewqeqw";
String sub="ewq";
System.out.println(IndexOf(s, sub));
}
public static int IndexOf(String s, String sub) {
char[] sChars = s.toCharArray();
char[] subChars = sub.toCharArray();
int sLength = s.length();
int subLength = sub.length();
int sIndex = 0;
int subIndex = 0;
while (sIndex < sLength && subIndex < subLength) {
if (sChars[sIndex] == subChars[subIndex]) {
subIndex++;
sIndex++;
} else {
sIndex = sIndex - subIndex + 1;
subIndex = 0;
}
}
int index = subIndex == subLength ? (subLength > 1 ? sIndex - subLength : sIndex - 1) : -1;
return index;
}
}