【问题标题】:splitting a string at arbitrary points lua在任意点分割字符串lua
【发布时间】:2015-08-15 01:58:51
【问题描述】:

我想在 lua 中定期拆分一个字符串,并在新行上显示每个新字符串。我的问题是拆分应该发生在任意用户定义的字符数之后,而不是任何特殊字符。目前我的代码是:

logfile = io.open("input.txt","r")
inputstring = logfile:read("*all")
for word in string.gmatch(inputstring, "TERRAIN_%a*") do 
j=1 
if j <= 64 then 
    io.write(word)
j=j+1
else
io.write(word,"\n")
    j=1
end

结束

我的意图是每次 string.gmatch 找到匹配项时,它都会将其写入一个新字符串并增加一个计数器。当计数器达到 64 时,它将插入一个新行。我希望比赛的长度是不规则的。

我不确定它的行为是否符合预期,或者这是我想要的格式化字符串的最佳方法。我很感激任何帮助。

【问题讨论】:

    标签: regex string lua split string-formatting


    【解决方案1】:

    请注意,您必须在循环外初始化计数器。

    local logfile = io.open("input.txt","r")
    local inputstring = logfile:read("*all")
    local j = 0;
    for word in string.gmatch(inputstring, "TERRAIN_%a*") do 
        j = j + 1;
        io.write(word);
        if j == 64 then
            io.write'\n';
            j = 1 -- reset the counter
        end
    end
    

    【讨论】:

    • 哈-谢谢。输出看起来更接近我的预期。
    猜你喜欢
    • 2017-05-18
    • 2013-11-23
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多