这里的问题是您提到的缺少分隔符 - 这使得软件无法知道单词的开始和结束位置。
鉴于你知道会出现的单词,我的技巧是这样的:
注意:这并没有考虑到单词重叠的可能性,并假设没有一个单词是其他单词的可能子集...
- 迭代已知单词
- 搜索 (indexOf) 每个已知单词的字符串并记下它在字符串中的位置
- 按索引值对值进行排序
- 使用找到的顺序中包含的值生成一个数组
/**
* This assumes that:
* - Input words are not subsets of other input words
*/
// Find all indices of the input word in the input String
function findAll(inputString, inputWord) {
const indices = [];
let index = 0;
while (index < inputString.length) {
index = inputString.indexOf(inputWord, index);
if (index == -1) break; // -1 means not found so we break here
indices.push({ index, word: inputWord });
index += inputWord.length;
}
return indices;
}
// Split the words into an array of Objects holding their positions and values
function splitWords(inputString, inputWords) {
// For holding the results
let results = [];
// Loop the input words
for (const inputWord of inputWords) {
// Find the indices and concat to the results array
results = results.concat(findAll(inputString, inputWord));
}
return results;
}
// Sort the words and return just an array of Strings
const orderWords = (inputArr) => inputArr.sort((a, b) => a.index - b.index).map(input => input.word);
/**
* Usage like so:
*/
const myString = 'onetwothreefourfivesixseveneightnineteneleventwelvethirteenfourteen';
const inputWords = ["one", "two", "three","four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen"];
const result = splitWords(myString, inputWords);
const ordered = orderWords(result);
console.dir(ordered);
/**
* Result:
[
'one', 'two',
'three', 'four',
'five', 'six',
'seven', 'eight',
'nine', 'ten',
'eleven', 'twelve',
'thirteen', 'four',
'fourteen'
]
*/