开发者

Need help when comparing strings

开发者 https://www.devze.com 2023-03-18 02:52 出处:网络
need help checking if a text contains a string to search for. Say that I have a text \"somerandomtextstringexampleexample_1\"

need help checking if a text contains a string to search for.

Say that I have a text

"somerandomtextstringexampleexample_1"

And I want to compare with for example this String

"example_1_e23wet_est1"

Now because the text contains "example_1" I want the function to return "example_1" and not also "example". (But if the string would have been "example_4_e23wet_est1" it should have returned just "example)

So the function takes 2 arguments

function searchForString(text,stringToCompare){
var foundstring;
.开发者_如何转开发..
if(foundstring)
return foundstring//In this case "example_1"
}

But then I'm pretty lost on how to carry on here since "indexOf" don't work here.

Thanks in advance =)


Well if you want the largest common substring, you might want to have a look here : largest common substring implementation and at this discussion about suffix tree for that matter :)


Call searchForString("somerandomtextstringexampleexample_1", "example_1_e23wet_est1");

It returns a list of matches. For example in this case: ["e", "ex", "example", "e", "example_1", "e"]... Take the greatest.

function searchForString(text, searchString) {
    var i, max, match = '', matches = [], str;

    function matchingStr(string, searchString) {
        var i = 0, 
            j = 0, 
            matchStr = '',
            strLength = string.length,
            sstrLength = searchString.length;

        while (string[i] === searchString[j] &&
               i < strLength &&
               j < sstrLength) {

            matchStr += string[i];
            i++;
            j++;
        }

        return matchStr;
    }

    for (i = 0, max = text.length; i < max; i++) {
        str = (i === 0) ? text : text.slice(i, max);
        console.log("str: " + str);
        console.log(match);
        match = matchingStr(str, searchString);    

        if (match.length !== 0) {
            matches.push(match);
        }         
    }    
  return matches;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号