//功能:暴力字符匹配.找到返回下标位置,未找到返回-1 public class BF { public static void main(String[] args) { String str1="hdlloworld-helloworld"; String str2="ell"; int index = new BF().bf(str1.toCharArray(),str2.toCharArray()); System.out.println(index); } private int bf(char[] str1, char[] str2) { int i = 0; int j = 0; while ( i<str1.length && j<str2.length){ if(str1[i]==str2[j]){ i++; j++; }else { i=i-j+1; j=0; } } if(j==str2.length){ return i-j;//找到的位置 }else { return -1; } } }