字符串操作/ Lua中的处理,字符串中单词的旋转

时间:2014-08-28 11:10:56

标签: string lua concatenation lua-table

我正在尝试实现一个在Lua中旋转字符串的函数,如下所示: rotatingString = string.rotate(originalStringValue,lengthOfRotation,directionOfRotation)

例如,我的输入字符串=“旋转并操纵字符串” 而且,我希望函数能够为我提供如下输出字符串(基于旋转长度和旋转方向): 输出字符串示例1:“字符串操作和旋转”

2 个答案:

答案 0 :(得分:4)

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))
print(rot(3,true))
print(rot(4,true))
print(rot(6,true))
print(rot(1,false))
print(rot(2,false))
print(rot(5,false))

每个字符串创建一次该函数(如对象),然后您可以向左或向右旋转字符串。请注意,当您向右旋转时,它会按字的反方向读取字符串(这类似于圆形的单词列表,您可以顺时针或逆时针方向移动它)。这是程序输出:

D:\Dev\Test>lua5.1 strrotate.lua
hello lua world. wassup there!
wassup there! hello lua world.
there! hello lua world. wassup
lua world. wassup there! hello
there! wassup world. lua hello
wassup world. lua hello there!
hello there! wassup world. lua

答案 1 :(得分:0)

这可以通过单个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

您需要决定如何处理空白。上面的代码保留了旋转的单词中的空格,但不包括它们。