我试图找到字符串中第一对重复的单词,但我只能按照句子中第一个单词的顺序找到所有重复的单词对,而不是按第一对。例如,在字符串“我非常爱我的安东尼,全心全意地爱”中,输出应该是我的,但它给了我爱。
let Sentence = 'I love my anthony so much with all my hearts love';
function wordRepeat(str) {
let splitStr = str.split(' ');
let list = [];
for (let i = 0; i < splitStr.length; i++) {
for (let j = i + 1; j < splitStr.length; j++) {
if (splitStr[i].match(splitStr[j])) {
//repeat = splitStr[i];
list.push(splitStr[i]);
}
}
}
//console.log(list);
return list[0];
}
console.log(wordRepeat(Sentence));
输出应该是“my”,但我得到“love”,但是“my”是正确答案,因为它是第一对。
最佳答案
你可以使用这样的东西:
function getDuplicate(inString){
const arr=inString.split(/\W+/g);// This is a Regular Expression - See it in use at https://regex101.com/r/X0Cyxx/1
return arr.find( (word,index) =>
arr.slice(0,index).includes(word)
);
}
EDIT: I modified line 2 to include punctuation, as @Phil suggested. Thanks, @Phil!
关于javascript - 如何在没有 hashmap 的情况下找到字符串中的第一对重复单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58422823/