String.indexOf()の実現方式
2913 ワード
//
public static int indexOf(byte[] source, byte[] target) { // byte[] source, byte[]target
int sourceCount = source.length;
int targetCount = target.length;
byte first = target[0];
int max = (sourceCount - targetCount);
for (int i = 0; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) { // source target
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 = 1; j < end && source[j] == target[k]; j++, k++) // j source target +1;k target +1
;
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
}
転載先:https://www.cnblogs.com/zhangit/p/7885810.html