package com.lkb.demo.test; public class StringTest { public static void main(String[] args) { StringTest test = new StringTest(); char[] src = {'c','d','d','c','d','c'}; char[] target = {'c','d','c'}; int index = test.getIndex(src, target); System.out.println(index); int index2 = test.getIndexByBF(src, target); System.out.println(index2); } /** * String.indexOf(String str)的原理 * 串与串之间的比较 * 1、先找子串的头在目标串中匹配的位置 * 2、如果找到,再接着比较 * 3、如果没找到,接着找,知道找遍主串 * @param src * @param target * @return */ public int getIndex(char[] src, char[] target){ char begin = target[0]; //头 int index = -1; for(int i=0;i<src.length;i++){ if(src[i] == begin){//找到头 int beginIndex = i; int j = 0; while( j < target.length && beginIndex < src.length){ if(src[beginIndex] == target[j]){ beginIndex++; j++; } else break; } if(j == target.length) return (index = i); } } return index; } /** * Brute-Force 暴力匹配 * 每个字符一一匹配 * @param src * @param target * @return */ public int getIndexByBF(char[] src, char[] target){ int index = -1; for(int i=0;i<src.length;){ int j; for(j=0;j<target.length;){ if (src[i] == target[j]) {//字符匹配 i++; j++; }else{ i++; break; } } if(j == target.length) index = i - j; } return index; } }