1. 程式人生 > >專案開發感悟——字串比較

專案開發感悟——字串比較

最近專案中用到了字串比較,要求省份--城市--區域與地址做對比,如果地址包含區域的字串就返回true.

我的實現方式是打算用將兩個字串每一個字元進行比較,直到省份--城市--區域遍歷完畢。

這麼做問題的確是解決了,但是我想到String類庫裡面indexOf是能解決了,但是我也不甘於僅僅是使用類庫,因此我打算看下indexOf原始碼。

 /**
*獲取字串的的位置
**/
 public int indexOf(String str) {
        return indexOf(str, 0);
    }


/**
*從指定索引處獲取子串的位置
*/
 public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }


/**
*
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        //逐個字元進行比較
        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* 查詢第一個字元. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }


 public int indexOf(int ch) {
        return indexOf(ch, 0);
    }


 public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }