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

如何合并两个Lua字符串,得到目标结果"hello world!"?

解决Lua字符串合并问题

要实现将两个互补字符串合并成目标结果,可按以下步骤操作:

核心思路

遍历两个字符串的每个对应位置,优先取第一个字符串的非空格字符;若第一个是空格,则取第二个字符串的非空格字符;若两者都是空格,则保留一个空格。最后清理连续空格并去掉首尾多余空格,得到整洁结果。

代码实现

local String1 = "h l o w r d"
local String2 = " e l   o l !"
local result = ""
local maxLength = math.max(#String1, #String2)

-- 遍历每个字符位置
for i = 1, maxLength do
    local char1 = String1:sub(i, i)
    local char2 = String2:sub(i, i)
    
    if char1 ~= " " then
        result = result .. char1
    elseif char2 ~= " " then
        result = result .. char2
    else
        -- 两个都是空格,保留一个
        result = result .. " "
    end
end

-- 清理连续空格并去除首尾空格
result = result:gsub("%s+", " "):match("^%s*(.-)%s*$")

print(result) -- 输出: hello world!

代码解释

  1. 遍历对应位置:用math.max获取两个字符串的最大长度,确保每个位置都被处理到。
  2. 字符选择逻辑:优先保留第一个字符串的有效字符,其次是第二个,空格位置仅保留单个空格。
  3. 清理空格:通过gsub("%s+", " ")将连续空格替换为单个,再用match去除首尾多余空格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:47:21