检查字符串之间的单词不匹配



这是一个代码,如果你记录words1[i],它将输出两个字符串中的所有匹配单词。我稍微更改了代码以检查不匹配的单词,但没有成功。假设我们有两个字符串:

var str1 = "world is beautiful";
var str2 = "is world butiful";

然后代码的输出将是(在控制台上):

(2) ["是"、"美丽"]

(2) ["世界"、"美丽"]

我们如何记录字符串之间的不匹配单词?

输出应该是一个结果数组,如下所示:

[美丽]

这是我尝试过的:

var str1 = "world is beautiful";
var str2 = "is world bautiful";
var words1 = str1.split(/s+/g),
    myArray = str1.split(/s+/g),
    words2 = str2.split(/s+/g),
    i,
    j;
for (i = 0; i < words1.length; i++) {
    for (j = 0; j < words2.length; j++) {
        if (words1[i].toLowerCase() == words2[j].toLowerCase()) {
        output = myArray.filter( ( el ) => !words1[i].includes( el ) );
        console.log(output);   
        }
    }
}

似乎因为 words1[i] 不是一个数组,所以整个代码不起作用。

有什么建议吗?

要在结果中多次使用相同的值,您可以使用包括

let a = "sent erth protect it".split(' ');
let b = "sent to earth to protect it".split(' ');
let res = b.filter(i => !a.includes(i));
console.log(res);

或者正如 @Dhananjai Pai 所指出的那样,创建一个 Map 并使用 get 检查键的值是否为 true

let map = new Map();
"sent erth protect it".split(' ').forEach(x => map.set(x, true));
let res = "sent to earth to protect it".split(' ').filter(x => !map.get(x));
console.log(res);

对不起,但要改写你的问题,你想做两个数组,一个是匹配的单词,另一个是不匹配的单词。

为了获得最佳性能,您可以使用第一个字符串的单词创建各种哈希图,并查看第二个字符串的单词是否在映射中,并相应地添加到任一结果数组中。

你可以在 JavaScript 中使用简单的对象或 Map 来模拟哈希图结构。下面的代码只列出了noMatchWords数组。如果您希望 matchWords 和 noMatchWords 在同一循环中,请使用 reduce 方法,并使用两个数组将单词推送到累加器对象

let str1= 'world is beautiful' , str2 = 'is world butiful';
wordMap = str1.split(' ').reduce((map,word) => { map[word.toLowerCase()] = true; return map; },{});
noMatchWords = str2.split(' ').filter(word => !wordMap[word.toLowerCase()]);
console.log(noMatchWords) // prints ['butiful'] since it is not in the first string. You can replace str1 and str2 in the steps 2 and 3 if you want to print words in str1 and not in str2 ie, get ['beautiful']

最新更新