我有一个字符串,例如“你好,我的名字是詹姆斯,你叫什么名字,你叫什么名字” 它应输出“你好我的名字是詹姆斯和你的3 6 7 4 8 3” 所以基本上发生的是,如果单词重复,那么它们将被第一个单词出现位置的位置替换。例如,如果句子是“房子是最好的”,它将用第一个“the”发生位置的“the”替换重复的单词。所以它应该输出“房子是最好的”
答案 0 :(得分:1)
首先,您要在每个空格处拆分字符串。您可以使用split
方法执行此操作。
var sentence = "hello my name is James and what is your name and what is your name";
var words = sentence.split(" ");
然后你想要两个嵌套的for
循环。第一个单词通过每个单词,第二个单词检查每个单词。如果它们是相同的,那就是
for (var i = 0; i < words.length; i++) {
for (var j = 0; j < i; j++) {
if (words[i] == words[j]) {
words[i] = j + 1;
break;
}
}
}
然后你想把数组转回一个字符串。使用join
方法执行此操作。
var newSentence = words.join(" ");
如果有标点符号或大写字母,则此方法无法正常工作。可以使用原始字符串上的toLowerCase
方法修复大写字母。标点符号会更复杂,如果你给我一些时间,我就能搞清楚。
答案 1 :(得分:0)
使用reduce
最简单:
function parse (str){
var found = {},
index = 0;
return str
.split(" ")
.reduce( (prev, el) => {
if(!found[el]){
found[el] = index;
prev.push(el)
} else {
prev.push(found[el])
}
index ++;
return prev;
}, []).join(" ");
}
console.log(parse('Hellow my my my my friend this this not this is not working with UpperCase This My hellow'));
&#13;