自己写出string类的indexof方法?
用些我们经常用的jdk方法其实是我们学习程序设计的最好的教材。
static int indexOf2(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount, int fromIndex) {
char first = target[0];
int max = sourceCount - targetCount;
for (int i =0; 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 = i + targetCount;
for (int k = 1; j < end
&& source[j] == target[k]; j++, k++)
;
if (j == end) {
/* Found whole string. */
return i ;
}
}
}
return -1;
}
用些我们经常用的jdk方法其实是我们学习程序设计的最好的教材。