版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Stu_zkl/article/details/82714412
String中有个常用的功能是indexOf(String str) ,该方法的功能是返回指定字符串第一次出现的字符串内的索引。如果没有则返回-1。
如果自己实现,就是暴力子字符串查找算法。
pat ,需要匹配的字符串,下面称为模式
txt ,本查找的文本
使用一个指针i跟踪文本,一个指针j跟踪模式。对于每个i,代码首先将j重置为0并不断增大,直至找到了一个不匹配的字符或模式结束(j == M)为止。
public static int search(String pat, String txt) {
int M = pat.length();
int N = txt.length();
for (int i = 0; i <= N - M; i++) {
int j = 0;
for ( j = 0; j < M; j++) {
if (txt.charAt(i + j) != pat.charAt(j)) {
break;
}
}
if (j == M ) return i; // 找到匹配
}
return -1; // 未找到匹配
}
再看看Java String indexOf(String str) 源码
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,
String target, int fromIndex) {
return indexOf(source, sourceOffset, sourceCount,
target.value, 0, target.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); // 如果模式长度等于0,直接返回文本总长度,否则返回-1 ,未匹配
}
if (fromIndex < 0) { // 开始匹配位置 < 0
fromIndex = 0;
}
if (targetCount == 0) { // 模式长度 == 0
return fromIndex;
}
char first = target[targetOffset]; // first 为模式第一个字符
int max = sourceOffset + (sourceCount - targetCount); // max= 0 + (文本长度- 模式长度) // 最终(最坏情况),模式第一个字符匹配的位置。
for (int i = sourceOffset + fromIndex; i <= max; i++) {
// i = 开始匹配位置+0
/* Look for first character. */
if (source[i] != first) { // 找到第一个匹配的字符
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
// 到这里时,要么匹配到第一个字符(i <= max),要么没有匹配到( i > max )
if (i <= max) {
int j = i + 1; // j = 第一个匹配字符的下一个
int end = j + targetCount - 1; // end = j + 模式长度 - 1
// k = 模式第二个字符 -> 最后,
// j = 第一个匹配字符 -> 匹配完,或者匹配失败
// end = 当前匹配的第一个字符 + 模式长度 - 1 (循坏条件)
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
// 匹配 成功,返回对应开始下标 即i-文本offset
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}