作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在字符串中找到第一对重复的单词,但我只能按照句子中第一个单词的顺序找到所有重复的对,而不是第一对。例如在字符串“I love my anthony so much with all my hearts love”中,输出应该是我的,但它给了我爱。
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/
我是一名优秀的程序员,十分优秀!