如何按规则拆分含变量标识的字符串数组元素?
问题描述
给定如下字符串数组:
[ "First sentence ", "Second sentence", "Third sentence {variable}", "Fourth sentence {variable} with other data {variable2}", "Fiftth sentence {variable} with additional data {variable2}", "Sixth sentence" ]
需要按照以下规则拆分数组元素:
- 若元素中存在
{变量名}格式的变量,且变量之后还有内容,则将该行拆分为两行:第一行保留到变量结尾(包括}),第二行保留变量之后的内容 - 若变量后无内容,则保持该行原样
期望输出数组:
[ "First sentence ", "Second sentence", "Third sentence {variable}", "Fourth sentence {variable}", "with other data {variable2}", "Fiftth sentence {variable}", "with additional data {variable2}", "Sixth sentence" ]
尝试了以下TypeScript代码,但无法得到预期结果:
convertLogicsArray(sentenceArray: string[]): string[] { const newSentenceArray: string[] = [] for (const sentence of sentenceArray) { // Split the sentence into two parts at the variable. const parts = sentence.split('{', 1) // If there is text after the variable, make the sentence two lines. if (parts.length === 2) { newSentenceArray.push(parts[0]) newSentenceArray.push(parts[1]) } // Otherwise, leave the sentence as one line. else { newSentenceArray.push(logic) } } return newSentenceArray }
修正后的代码及说明
原代码存在几个问题:
split('{', 1)用法错误:split的第二个参数是限制返回数组的最大长度,设置为1只会返回包含原字符串的单元素数组,永远触发else分支- 变量名错误:else分支中使用了未定义的
logic,应为当前遍历的sentence - 拆分逻辑不准确:未定位到变量结束的位置(
}),无法正确拆分出包含完整变量的第一部分
以下是修正后的代码:
convertLogicsArray(sentenceArray: string[]): string[] { const newSentenceArray: string[] = []; for (const sentence of sentenceArray) { // 定位第一个变量结束后跟着空格的位置(确保变量后有内容) const splitIndex = sentence.indexOf('} '); if (splitIndex !== -1) { // 截取包含完整变量的第一部分 const firstPart = sentence.slice(0, splitIndex + 1); // 截取变量之后的剩余内容 const secondPart = sentence.slice(splitIndex + 2); newSentenceArray.push(firstPart, secondPart); } else { // 变量后无内容或无变量,直接保留原句 newSentenceArray.push(sentence); } } return newSentenceArray; }
关键逻辑说明:
- 用
indexOf('} ')精准定位需要拆分的位置,确保变量后确实有后续内容 - 通过
slice方法拆分字符串,第一部分保留到变量结尾,第二部分从变量后的空格开始截取 - 若找不到
}则无需拆分,直接将原句加入结果数组
内容的提问来源于stack exchange,提问作者CraZyDroiD
相关产品推荐
相关产品推荐

