Luc*_*a93 5 string lua gsub lua-patterns
我正在尝试使用一些操作字符串的函数在Lua中创建一个库.我想做一个函数,只在单词的奇数字符上将字母大小写改为高位.
这是一个例子:
Input: This LIBRARY should work with any string!
Result: ThIs LiBrArY ShOuLd WoRk WiTh AnY StRiNg!
Run Code Online (Sandbox Code Playgroud)
我尝试使用"gsub"功能,但我发现它很难使用.
这几乎可以工作:
original = "This LIBRARY should work with any string!"
print(original:gsub("(.)(.)",function (x,y) return x:upper()..y end))
Run Code Online (Sandbox Code Playgroud)
当字符串的长度为奇数且最后一个字符为字母时,它将失败,例如
original = "This LIBRARY should work with any strings"
Run Code Online (Sandbox Code Playgroud)
我将把这种情况留作练习。
首先,将字符串拆分为单词数组:
local original = "This LIBRARY should work with any string!"
local words = {}
for v in original:gmatch("%w+") do
words[#words + 1] = v
end
Run Code Online (Sandbox Code Playgroud)
然后,创建一个函数将单词(如预期)、奇数字符转为大写、偶数字符转为低写:
function changeCase(str)
local u = ""
for i = 1, #str do
if i % 2 == 1 then
u = u .. string.upper(str:sub(i, i))
else
u = u .. string.lower(str:sub(i, i))
end
end
return u
end
Run Code Online (Sandbox Code Playgroud)
使用该函数修改每个单词:
for i,v in ipairs(words) do
words[i] = changeCase(v)
end
Run Code Online (Sandbox Code Playgroud)
最后,使用table.concat来连接一个字符串:
local result = table.concat(words, " ")
print(result)
-- Output: ThIs LiBrArY ShOuLd WoRk WiTh AnY StRiNg
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
814 次 |
| 最近记录: |