获取字符串中整个单词与javascript中其余单词的组合



我有以下字符串句子作为输入

'test string of whole words'

作为输出,我需要一个包含不同单词组合的字符串数组,包括像这样的其余单词

test string of whole words
teststring of whole words
test stringof whole words
test string ofwhole words
test string of wholewords
teststringof whole words
test stringofwhole words
test string ofwholewords
teststringofwhole words
test stringofwholewords
teststringofwholewords

我试着写下面的代码来实现上面的输出,但它只能一次删除一个空间。这个代码只是我的试用。不需要更新/扩展它,如果它是错误的方式。你可以从头开始

function getSpaceIndices(str) {
let spaceIndices = []
for (let i = 0; i < str.length; i++) {
if (str[i] === " ") {
spaceIndices.push(i)
}
}
return spaceIndices
}
let str = 'test string of whole words'
let strArray = str.split(" ");
let combinationArray = []
// let spaceRemoveCount = 1
let spaceIndices = getSpaceIndices(str)
let currentIndex = 0
while (currentIndex < spaceIndices.length) {
let tempStr = str.slice(0, spaceIndices[currentIndex]) + str.slice(spaceIndices[currentIndex] + 1);
combinationArray.push(tempStr);
currentIndex++
}
console.log(combinationArray);

请帮助从上述输入字符串

实现上述输出数组

使用递归应该能够相当容易地做到这一点,只是作为一个开始,您可以尝试如下

function getSpaceIndices(str) {
let spaceIndices = []
for (let i = 0; i < str.length; i++) {
if (str[i] === " ") {
spaceIndices.push(i)
}
}
return spaceIndices
}
let str = 'test string of whole words'
let strArray = str.split(" ").filter(s => s != " ");
let combinationArray = []
// let spaceRemoveCount = 1
/*
let spaceIndices = getSpaceIndices(str)
let currentIndex = 0
while (currentIndex < spaceIndices.length) {
let tempStr = str.slice(0, spaceIndices[currentIndex]) + str.slice(spaceIndices[currentIndex] + 1);
combinationArray.push(tempStr);
currentIndex++
}
console.log(combinationArray);
*/
function print(str,current, start, merge){
let s = ""
if(merge){
s =current+str[start];
}
else{
s = current+" "+str[start]
}
start++;
if(start >= str.length){
console.log(s);
return;
}
print(str,s,start,true);
print(str,s,start,false);


}
print(strArray,"",0);

最新更新