闲的没事 就是想看一下 Java 用的啥算法 查找 字符串匹配
String s = new String("aaa");
s.contains("a");
追到 String 源码 就是用的 indexOf 这个 方法
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);
}
转成 character 数组 进行 搜索🔍 可以 学到 target.value 用 String 转 数组
/** * Code shared by String and StringBuffer to do searches. The * source is the character array being searched, and the target * is the string being searched for. * * @param source the characters being searched. * @param sourceOffset offset of the source string. * @param sourceCount count of the source string. * @param target the characters being searched for. * @param targetOffset offset of the target string. * @param targetCount count of the target string. * @param fromIndex the index to begin searching from. */
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;
}// 从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);// 注意⚠️ for 循环♻️内部的 i跟着一起 变呢
}
/* 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++);// 一个一个匹配 同时 更新 j++
if (j == end) { // ✅匹配成功 就返回
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;// 🙅♂️ 到最后也没成功 ❌
}
我以为多神奇的 匹配 原来就是 一个一个的匹配 哈哈 唯一的 优化 就是 先匹配第一个 字符 第一个字符 对上了后面就 循环遍历
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有