的ATLEAST n个,说3的Javascript匹配两个字符串我想匹配字符串的字符至少n个字符
例如,如果我有两句话,我想返回,如果两个词真有一个共同的子字符3个字符
即,如果我匹配加利福尼亚州和Unical,我想要成为真实的,因为两者都有“Cal”作为常用字符串。
的ATLEAST n个,说3的Javascript匹配两个字符串我想匹配字符串的字符至少n个字符
例如,如果我有两句话,我想返回,如果两个词真有一个共同的子字符3个字符
即,如果我匹配加利福尼亚州和Unical,我想要成为真实的,因为两者都有“Cal”作为常用字符串。
function findCommonSubstring(s1, s2, n) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
var min = s1.length < s2.length ? s1 : s2;
var max = min == s1 ? s2 : s1;
if(n <= 0 || n > min.length) {
return false;
}
var substring;
for(var i=0; i<=min.length-n; i++) {
if(max.indexOf((substring = min.substring(i, i+n))) > -1) {
return substring;
}
}
return false;
}
电话:
alert(findCommonSubstring("California", "Unical", 3));
打印:
cal
函数应该考虑到用户使用n <= 0并返回false的场合 – MIrrorMirror
@MIrrorMirror如果用户使用'n <= 0','for'循环根本就不会有任何迭代和函数然后会返回'false'。 – sp00m
谢谢..它工作得很好.. – user1817701
function matchStrings(s1, s2, charnum) {
var found = false;
var i = 0;
if (charnum>0 && charnum<s2.length) {
s1=s1.toLowerCase();
s2=s2.toLowerCase();
for (i=0; i<=s2.length - charnum; i++) {
if (s1.indexOf(s2.substr(i, charnum)) > -1) {
found = true;
break;
}
}
}
return found;
}
当'i = 1'时,如果在's1'中找到's2'的第一个字符,该函数返回'true'? – gefei
确实,我很懒。现在更正 – MIrrorMirror
也是错误的。它只检查是否在s1 – gefei
function test(first,second,nl)
{
first=first.toLowerCase();
second=second.toLowerCase();
if(first.length>second.length)
{
var len=first.length ;
}
else
{
var len=second.length;
var t=first;
first=second;
second=t;
}
//var len=first.length>second.length?first.length:second.length;
var count=0;
while(len>=nl)
{
str=first.substr(count,nl);
if(second.indexOf(str)!=-1)
{
return str;
break;
}
count++;
len--;
}
return false;
}
alert(test('Cal','unicbbl',4))
alert(test('California','unicali',3));
alert(test('California','unicali',4));
[test here][1]
[1]: http://jsfiddle.net/tuMRg/5/
混淆解决方案是错误的。这里证明: http://jsfiddle.net/tuMRg/3/尽管事实上两个字符串没有4个字符的公共子字符串,它返回“l”。 – MIrrorMirror
在这种情况下,您必须确定要搜索的字符串以及要搜索的字符串,字符数也应小于要搜索的字符串长度。 –
以下是相当复杂,但如果您从大型内容中搜索字符串,这是一个不错的选择。它从筛选可能的匹配开始,然后测试这些可能性。
var atLeastMatch = function(search, content, atLeast) {
var search = search,
content = content,
regex = new RegExp('[' + search + ']{' + atLeast + ',}', "i", "g"),
possibleMatches = content.match(regex);
for (var i = 0, j = possibleMatches.length; i < j; i++) {
if (possibleMatches[i].length > atLeast) {
for (var k = 0, l = possibleMatches[i].length - atLeast; k <= l; k++) {
if ((new RegExp(possibleMatches[i].slice(k, k + atLeast), "i")).test(search)) {
return true;
}
}
} else {
if ((new RegExp(possibleMatches[i], "i")).test(search)) {
return true;
}
}
}
return false;
}
console.log(atLeastMatch('California', 'Unical', 3));
你试过什么了吗? – sp00m
http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm –