首页 > 解决方案 > Lua 字符串操作

问题描述

一个字符串'321@322@323@324@325'。这里每个数字的位数是 3,但不限于 3,它可以是任何数字。这是一个字符串中的 5 个数字,但这个数字可以是任何数字。任务是获取 321,322,323,324,325 并存储在表中,以便可以对它们执行任何操作。
我尝试了几个字符串函数,如 c = c:gsub('%W','') 来消除那些非字母数字字符,但没有任何帮助。

function encrypter()--FUNCTION 14
    c=' '
    print('Please enter your message!')
    local message=io.read()
    lengthOfString=string.len(message)--Inbuit function to get length of a string.
    newLine()
    print('Please enter your key. Remember this key, otherwise your message wont be decrypted')
    newLine()
    key=io.read()
    key=tonumber(key)
    largeSpace()
    print("Encrypted message is")
    for s=1,lengthOfString do
        --print(encryptionFormula(string.byte(message,s),key))
        --inbuilt function for converting character of a string to it's respective ASCII value. First place gets character or variable having string whereas second place gets position of that character in the given string.
        b=encryptionFormula(string.byte(message,s),key)
        c=c..tostring(b)..'@'
        --print(c)
        b=0
    end
    print(c)
    largeSpace()
    print("Now share this message along with the key to the receiver. Don't share your key with anyone, if you don't want your message to be read.")
end

标签: lua

解决方案


您正在寻找的是string.gmatch().

local input = "123@546514@13@548@2315"

local numbers = {}
for number in string.gmatch(input, '%d+') do
   table.insert(numbers, number)
end

-- Output the numbers

for index, number in ipairs(numbers) do
   print(index, number)
   -- This prints:
   -- 1 123
   -- 2 546514
   -- 3 13
   -- 4 548
   -- 5 2315
end

如果你不知道 Lua 模式是如何工作的,你可以在参考手册中阅读它们,或者你可以看看Programming in Lua(第一版在他们的网站上免费提供)


推荐阅读