如何在不替换重复值的情况下替换字符

我想做类似于 ('hello i am hello i is'):gsub('hello', 'hola') 这样的事情,但不会使字符串 'hola i am hola i is' 而是 'hello i am hola i is'

我不知道如何解决这个问题,因为这可能需要复杂的字符串操作,而我在字符串操作方面只有 4/10 的水平。

我想避免使用 string.subfor loops,但如果需要使用它们,我也可以。

请帮我解决这个问题

点赞
用户2858170
用户2858170

一个简单的方法来替换 "hello" 出现的次数是

local text = "hello I am hello I am hello"
local count = 0
local replace = 2
print((text:gsub("hello", function()
  count = count + 1
  if count == replace then
    return "hola"
  end
end)))

打印 hello I am hola I am hello

或者:

print(text:gsub("hello", "hola", 2):gsub("hola", "hello", 1))

这样你就将前两个 hello 替换为 hola,然后将第一个 hola 替换为 hello。当然,这只适用于字符串的这一部分中没有其他的 hola

2021-05-11 09:20:42