You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多词字符串分配至数组?指定格式拆分字符串方法

如何将多词字符串按双词组分配到数组中?

Great question! Let's walk through how to split your specific string into pairs of words, and I'll cover the general approach so you can adapt it to other cases too.

核心思路

The key steps here are straightforward:

  • 拆分原字符串为单个单词数组:先把完整的消息拆成每个元素对应一个单词的列表(像"It's"这种带省略号的词会被正确识别为单个单词)。
  • 将单词两两分组:遍历单词列表,每次取连续的两个单词合并成一个字符串。
  • 收集分组到目标数组:把每组合并后的字符串添加到你需要的数组里。

JavaScript 实现

下面是针对你给出的示例的JavaScript实现:

// 你的原始消息
const message = "It's wings are too small to get its fat little body off the ground";

// 第一步:拆分单个单词数组
// 使用 /\s+/ 可以处理任意数量的空格(你的示例里是单个空格,同样适用)
const words = message.split(/\s+/);

// 第二步:构建目标双词数组
const arr = [];
for (let i = 0; i < words.length; i += 2) {
  // 合并连续两个单词并推入数组
  arr.push(`${words[i]} ${words[i + 1]}`);
}

// 查看结果
console.log(arr);
// 输出:["It's wings", "are too", "small to", "get its", "fat little", "body off", "the ground"]

处理单词数为奇数的情况

如果你的字符串单词数是奇数(比如最后多一个单独的单词),可以加个判断优雅处理:

const arr = [];
for (let i = 0; i < words.length; i += 2) {
  if (i + 1 < words.length) {
    arr.push(`${words[i]} ${words[i + 1]}`);
  } else {
    // 单独剩下的单词直接加入(可根据需求调整逻辑)
    arr.push(words[i]);
  }
}

Python 实现

如果你用Python,也有对应的解决方案:

# 你的原始消息
message = "It's wings are too small to get its fat little body off the ground"

# 第一步:拆分单词列表(split() 默认按空白分割)
words = message.split()

# 第二步:构建目标双词列表
arr = []
for i in range(0, len(words), 2):
    # 合并连续两个单词
    arr.append(f"{words[i]} {words[i+1]}")

# 打印结果
print(arr)
# 输出:["It's wings", "are too", "small to", "get its", "fat little", "body off", "the ground"]

同样,处理奇数单词数的情况:

arr = []
for i in range(0, len(words), 2):
    if i + 1 < len(words):
        arr.append(f"{words[i]} {words[i+1]}")
    else:
        arr.append(words[i])

内容的提问来源于stack exchange,提问作者Liso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:38:15