串的模拟匹配是使用常规思路对串进行字串匹配
function String(string) {
this.data = string;
}
String.prototype.index =function(t){
var i=0;j=0;
while(i<this.data.length&&j<t.data.length){
if(this.data[i]==t.data[j]){
i++;j++;
}else{
i = i-j+1;j=0;
}
}
if(j>=t.data.length){
return i-t.data.length;
}else{
return -1;
}
}
var s = new String('google');
var s1 = new String('og');
var s2 = new String('gl');
var s3 = new String('e');
var s4 = new String('g');
var s5 = new String('aaaa');
console.info(s.index(s1));
console.info(s.index(s2));
console.info(s.index(s3));
console.info(s.index(s4));
console.info(s.index(s5));
输出
2
3
5
0
-1
网友评论