package cn.gl.work;

/**
 * Created by guoli on 2017/9/9 0009.
 * YXV0aG9yOiB6aGFuZ2d1b2xpLmNu
 */
public class StringIndexOf {

    public int IndexOf(String source, String target) {
        char[] sources = source.toCharArray();
        char[] targets = target.toCharArray();
        int sourceCount = sources.length;
        int targetCount = targets.length;
        char first = targets[0];
        int max = sourceCount - targetCount;
        for (int i = 0; i <= max; i++) {
            //1. 第一个字符相等
            if (sources[i] != first) {
                while (++i < max && sources[i] != first) {
                    ;
                }
            }
            //2、匹配2到子串
            if (i < max) {//未到最后
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = 1; j < end && sources[j] == targets[k]; j++, k++) {
                    ;//子串和原串截取的部分在循环对比
                }
                if (j == end) {//找到了
                    return i;
                }
            }
        }
        return -1;
    }
}

标签: Java, string

添加新评论