Java源码解读(二)——String中的indexOf(String)
前天面试,面试官给了我一小时,让我写一个判断子串的函数,我虽然想到了KMP,但是不知其实现原理,就写了个暴力算法。
今天看了一下Java源码中查找子串的函数,发现它们也是用的暴力(笑:先遍历父串,找到与子串第一个字符相同的字符的索引,再从该索引开始进行后面字符的比较,如果成功则返回该索引,否则从该索引后面继续寻找子串。
indexOf(String)
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); }
// 从source的fromIndex开始,寻找target static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { // 如果开始索引大于等于source长度,当子串长度等于0时返回source长度,否则返回-1 if (fromIndex >= sourceCount) { return (targetCount == 0 ? sourceCount : -1); } // 如果开始的索引小于0,强制使其从0开始 if (fromIndex < 0) { fromIndex = 0; } // 如果子串长度等于0,返回开始索引 if (targetCount == 0) { return fromIndex; } char first = target[targetOffset]; int max = sourceOffset + (sourceCount - targetCount); for (int i = sourceOffset + fromIndex; i <= max; i++) { /* Look for first character. */ 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; }
上一篇:
IDEA上Java项目控制台中文乱码