如何使用JavaScript将无分隔符连续英文单词字符串拆分为对应单词数组
实现思路
- 先预定义所有待匹配的目标单词集合,本次拆分场景为1~14的英文数字表述,直接列出所有目标单词即可
- 从原始字符串的起始位置开始遍历匹配单词集合,匹配到符合开头的单词后,将其存入结果数组,同时截断原始字符串移除已匹配部分
- 循环执行匹配逻辑,直到原始字符串被完全拆分
如果存在长单词包含短单词的歧义场景(比如同时匹配two和twelve),可以先将单词集合按长度降序排序,优先匹配更长的单词即可避免拆分错误。
完整JavaScript实现代码
// 原始待拆分字符串 const myString = "onetwothreefourfivesixseveneightnineteneleventwelvethirteenfourteen"; // 目标单词字典 const wordDict = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen"]; const splitContinuousStr = (str, dict) => { // 按单词长度降序排序,避免短单词优先匹配导致的拆分错误 const sortedDict = [...dict].sort((a, b) => b.length - a.length); const result = []; let remaining = str; while(remaining.length) { for(const word of sortedDict) { if(remaining.startsWith(word)) { result.push(word); remaining = remaining.slice(word.length); break; } } } return result; } const splitString = splitContinuousStr(myString, wordDict); console.log(splitString); // 输出结果:["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen"]
内容的提问来源于stack exchange,提问作者StianS
相关产品推荐
相关产品推荐

