且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Lua中修改字符串中的字符

更新时间:2023-02-19 12:44:55

Lua 中的字符串是不可变的.这意味着,任何替换字符串中文本的解决方案最终都必须构造一个具有所需内容的新字符串.对于将单个字符替换为其他内容的特定情况,您需要将原始字符串拆分为前缀部分和后缀部分,并将它们重新连接到新内容周围.

Strings in Lua are immutable. That means, that any solution that replaces text in a string must end up constructing a new string with the desired content. For the specific case of replacing a single character with some other content, you will need to split the original string into a prefix part and a postfix part, and concatenate them back together around the new content.

代码的这种变化:

function replace_char(pos, str, r)
    return str:sub(1, pos-1) .. r .. str:sub(pos+1)
end

是对简单 Lua 的最直接的翻译.对于大多数用途来说,它可能足够快.我已经修复了前缀应该是第一个 pos-1 字符的错误,并利用了如果 string.sub 的最后一个参数丢失它的事实假定为 -1,相当于字符串的结尾.

is the most direct translation to straightforward Lua. It is probably fast enough for most purposes. I've fixed the bug that the prefix should be the first pos-1 chars, and taken advantage of the fact that if the last argument to string.sub is missing it is assumed to be -1 which is equivalent to the end of the string.

但请注意,它会创建一些临时字符串,这些字符串将在字符串存储中徘徊,直到垃圾收集将它们吃掉.任何解决方案都无法避免前缀和后缀的临时性.但这也必须为第一个 .. 运算符创建一个临时对象,以供第二个使用.

But do note that it creates a number of temporary strings that will hang around in the string store until garbage collection eats them. The temporaries for the prefix and postfix can't be avoided in any solution. But this also has to create a temporary for the first .. operator to be consumed by the second.

两种替代方法之一可能会更快.第一个是 Paŭlo Ebermann 提供的解决方案,但有一个小调整:

It is possible that one of two alternate approaches could be faster. The first is the solution offered by Paŭlo Ebermann, but with one small tweak:

function replace_char2(pos, str, r)
    return ("%s%s%s"):format(str:sub(1,pos-1), r, str:sub(pos+1))
end

这使用 string.format 来组装结果,希望它可以猜测最终的缓冲区大小,而无需额外的临时对象.

This uses string.format to do the assembly of the result in the hopes that it can guess the final buffer size without needing extra temporary objects.

但请注意,string.format 可能会遇到任何通过其 %s传递的字符串中的任何