如何在字符串中获取单词的所有组合 [英] How to get all combinations of word in string
本文介绍了如何在字符串中获取单词的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望得到字符串中所有相邻的单词组合,例如
string 获取所有组合
我希望得到
I want to get all neighboring combinations of words in string like
string get all combinations
and I want to get
get all combinations
all combinations
get all
all
get
combinations
我写下一个代码
var string = 'get all combinations';
var result = getKeywordsList(string);
document.write(result);
function getKeywordsList(text) {
var wordList = text.split(' ');
var keywordsList = [];
while (wordList.length > 0) {
keywordsList = keywordsList.concat(genKeyWords(wordList));
wordList.shift();
}
return keywordsList;
}
function genKeyWords(wordsList) {
var res = [wordsList.join(' ')];
if (wordsList.length > 1) {
return res.concat(genKeyWords(wordsList.slice(0, -1)));
} else {
return res;
}
}
我可以改进或简化这项任务(让所有邻近的单词组合)
ps抱歉我的英语
can I improve or simplify this task (get all neighboring combinations of words ) p.s. sorry for my English
推荐答案
你好也许这可以帮到你
var string = 'get all combinations'
var sArray = string.split(' ');
var n = sArray .length;
for (var i = 0; i < n; i++) {
for (var j = 0; j <= i; j++) {
document.write(sArray .slice(j, n - i + j).join(' ') + ', ');
}
}
这篇关于如何在字符串中获取单词的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文