2014-08-28 171 views
2

我想实现的功能旋转在Lua字符串,像这样: rotatedString = string.rotate(originalStringValue,lengthOfRotation,directionOfRotation)字符串操作/处理在Lua,文字的旋转在一个字符串

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

+0

你的意思是*字*在字符串中的旋转? – lhf 2014-08-28 11:12:00

+0

你的例子中的'lengthOfRotation'是什么? – lhf 2014-08-28 11:12:31

+0

旋转n左边和-n右边有什么区别? – Deduplicator 2014-08-28 11:23:11

回答

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)) 

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

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 
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 

你需要决定如何处理空白。上面的代码保留了旋转文字中的空格,但不包围它们。