在Lua中的字符串处理,字符串中单词的旋转。

我正在尝试实现一个在Lua中旋转字符串的函数,类似于这样: rotatedString = string.rotate(originalStringValue, lengthOfRotation, directionOfRotation)

例如,我的输入字符串为“旋转和操作字符串” 我希望该函数根据旋转长度和旋转方向给我输出字符串,如下所示: 输出字符串示例1:“string manipulate and Rotate”

点赞
用户988143
用户988143
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

该函数针对每个字符串创建一次(类似于对象),然后您可以向左或向右旋转该字符串。请注意,当您向右旋转字符串时,它以单词的相反方向读取字符串(这类似于单词的循环列表,并且您正在按顺时针或逆时针遍历它)。以下是程序输出:

2014-08-28 13:44:22
用户107090
用户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