在Lua中的字符串处理,字符串中单词的旋转。
2014-8-28 11:34:56
收藏:0
阅读:90
评论:2
我正在尝试实现一个在Lua中旋转字符串的函数,类似于这样: rotatedString = string.rotate(originalStringValue, lengthOfRotation, directionOfRotation)
例如,我的输入字符串为“旋转和操作字符串” 我希望该函数根据旋转长度和旋转方向给我输出字符串,如下所示: 输出字符串示例1:“string manipulate and Rotate”
点赞
用户107090
这可以通过使用单个 gsub 函数和自定义的模式来解决。
请尝试以下代码:
s="The quick brown fox jumps over the lazy dog"
function rotate(s,n)
local p
if n>0 then
p="("..string.rep("%S+",n,"%s+")..")".."(.-)$"
else
n=-n
p="^(.-)%s+".."("..string.rep("%S+",n,"%s+").."%s*)$"
end
return (s:gsub(p,"%2 %1"))
end
print('',s)
for i=-5,5 do
print(i,rotate(s,i))
end
您需要决定如何处理空格。上面的代码保留了旋转后单词周围的空格,但不保留它们旋转的内部空格。
2014-08-28 14:12:03
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
local teststr = "hello lua world. wassup there!" local rotator = function(inpstr) local words = {} for i in string.gmatch(inpstr, "%S+") do words[#words+1] = i end local totwords = #words return function(numwords, rotateleft) local retstr = "" for i = 1 , totwords do local index = ( ( (i - 1) + numwords ) % totwords ) index = rotateleft and index or ((totwords - index) % totwords ) retstr = retstr .. words[ index + 1] .. " " end return retstr end end local rot = rotator(teststr) print(rot(0,true)) -- Hello lua world. wassup there! print(rot(3,true)) -- wassup there! Hello lua world. print(rot(4,true)) -- there! Hello lua world. wassup print(rot(6,true)) -- lua world. wassup there! Hello print(rot(1,false)) -- there! wassup world. lua Hello print(rot(2,false)) -- wassup world. lua Hello there! print(rot(5,false)) -- Hello there! wassup world. lua该函数针对每个字符串创建一次(类似于对象),然后您可以向左或向右旋转该字符串。请注意,当您向右旋转字符串时,它以单词的相反方向读取字符串(这类似于单词的循环列表,并且您正在按顺时针或逆时针遍历它)。以下是程序输出: