5、字符串匹配算法
从字符串S中查找是否存在字符串T,若存在返回所在位置,不存在返回-1(不能基于indexOf/includes等内置方法)
- 循环当前字符中的每一项,让每一项从后面截取
T.length
个字符,然后和T进行比较,不一样继续循环,应用返回当前索引
(function(){
function myIndexOf(T){
//this => S
let lenS = this.length,
lenT = T.length,
res = -1;
if(lenS < lenT){return -1;}
for(let i = 0;i <= lenS - lenT;i++){
if(T === this.substr(i,lenT)){
res = i;
break;
}
}
return res
}
String.prototype.myIndexOf = myIndexOf;
})()
let S = 'adhskdahskyuasjkdas',
T = 'yu';
console.log(S.myIndexOf(T))
- 正则处理
(function(){
function myIndexOf(T){
let reg = new RegExp(T)
res = reg.exec(this)
return res === null ? -1 :res.index;
}
String.prototype.myIndexOf = myIndexOf;
})()
let S = 'adhskdahskyuasjkdas',
T = 'yu';
console.log(S.myIndexOf(T))