Skip to content Skip to sidebar Skip to footer

How To Search One String For All Of The Words Contained In A Second String?

I need to check a string A for a match based on whether it contains all of the words in another string B - in whatever order. So, let's say string A is this: one two three four fiv

Solution 1:

  1. Split the strings into arrays of words.
  2. For each word in string A, assign obj[word] = true;.
  3. For each word in string B, check if obj[word] === true;. If it does not, return false.
  4. Return true.

This should be trivial enough to translate into code.

Solution 2:

// If the client has the array method every, this method is efficient-

functioncommonwords(string, wordlist){
    string= string.toLowerCase().split(/\s+/);
    wordlist= wordlist.toLowerCase().split(/\s+/);
    return wordlist.every(function(itm){
        returnstring.indexOf(itm)!= -1;
    });
}

commonwords('one two three four five','one two nine');

// If you want any client to handle it without a special function, you can 'explain' the advanced array methods-

Array.prototype.every= Array.prototype.every || function(fun, scope){var L= this.length, i= 0;
    if(typeof fun== 'function'){while(i<L){
            if(i inthis && !fun.call(scope, this[i], i, this)) returnfalse;
            ++i;
        }
        returntrue;
    }
    returnnull;
}
Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i< L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

Solution 3:

functioncompare(stringA, stringB) {
    // split for the wordsvar aa = stringA.split(/\s+/), ab = stringB.split(/\s+/);
    var ha = {}, hb = {};

    // use a hash of the wordsfor (var i = 0; i < aa.length; i ++) ha[aa[i]] = true;
    for (var j = 0; j < ab.length; j ++) hb[ab[j]] = true;

    // compare the two setsfor (var k in hb) if (!ha.hasOwnProperty(k)) returnfalse;
    returntrue;
}

Solution 4:

Why not just create a Set of the words in String A (Object with true values in JavaScript), and check if it contains each word in String B?

How are you defining "word"? Is string.split("\\s+"); sufficient, or are you doing something fancier?

Post a Comment for "How To Search One String For All Of The Words Contained In A Second String?"