Lua 字符串操作
这是我的代码
local function char(...) return string.char(...) end
local function addtok(text,token,C)
text = text or ""
local string = ""
local count = 0
for word in text:gmatch(("[^%s]+"):format(char(C))) do
string = string..char(C)..word
end
string = string..char(C)..token
print(string)
end
函数
addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)
返回
“;奉献光环;充电器;正义之怒;智慧印记”,
但我想要的是
“奉献光环;充电器;正义之怒;智慧印记”
可能的修复: print(string.sub (string, 2))
有更好的解决方案吗?
This is my code
local function char(...) return string.char(...) end
local function addtok(text,token,C)
text = text or ""
local string = ""
local count = 0
for word in text:gmatch(("[^%s]+"):format(char(C))) do
string = string..char(C)..word
end
string = string..char(C)..token
print(string)
end
The function
addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)
returns
";Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"
but what I want is
"Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"
possible fix: print(string.sub(string, 2))
any better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
string = string..char(C)..word
行将在前面添加第一个分号。这就是在循环内附加的问题 - 如果您不需要尾随或前导分隔符,则必须对最后一个或第一个元素进行例外处理。但在这种情况下,您应该使用table.concat
,这既是为了性能(避免不必要的字符串复制)又为了通过分隔符连接的方便性:The line
string = string..char(C)..word
will prepend the first semicolon. That's the issue with appending within a loop - you have to make an exception for either the last or the first element if you don't want a trailing or leading delimiter. In this case however, you should be usingtable.concat
, both for performance (avoiding unnecessary string copies) and convenience of joining by delimiter: