【问题标题】:How to split string in Lua with comma如何用逗号分割Lua中的字符串
【发布时间】:2014-07-14 19:00:58
【问题描述】:

我需要用有限的字符串(对我来说是逗号)或数组中的字符来分隔字符串。在 Lua 中如何用逗号分隔。

我检查了这些链接,但我不明白:

http://lua-users.org/wiki/SplitJoin

http://lua-users.org/wiki/PatternsTutorial

https://stackoverflow.com/questions/1426954/split-string-in-lua

objPropo = {}
str = "Maria Mercedez,,Jose,Sofia"
i = 1
for token in string.gmatch(str, ",") do
    objPropo[i] = token
    i = i + 1
end
native.showAlert("Names", objPropo[1], {"OK"})
native.showAlert("Names", objPropo[2], {"OK"})  <-- Is this error? Because is nil? or what happend?
native.showAlert("Names", objPropo[3], {"OK"})
native.showAlert("Names", objPropo[4], {"OK"})

它可以显示:

Maria Mercedez

如何格式化发送模式?

[其他选择]

如果可能的话?

objPropo = {}
str = "Maria Mercedez,,Jose,Sofia"
i = 1
for token in string.gmatch(str, ",") do
    objPropo[token] = token           <-------- CHECK
    i = i + 1
end
native.showAlert("Names", objPropo["Maria Mercedez"], {"OK"})
native.showAlert("Names", objPropo["Jose"], {"OK"})

对吗?

【问题讨论】:

    标签: string lua split coronasdk lua-patterns


    【解决方案1】:

    要用逗号分割字符串,需要使用匹配非逗号(后跟逗号)的模式:

    for token in string.gmatch(str, "([^,]+),%s*") do
        objPropo[i] = token
        i = i + 1
    end 
    

    【讨论】:

    • 谢谢,但我解决了这个问题:string.gmatch(event.result, "[^,]+")
    • @Ryuchan 如果你想要的话,名字前会包含空格。
    • 名称前不包含空格。现在,我做了编辑。我想知道如果逗号之间没有字符会发生什么。
    猜你喜欢
    • 2017-05-18
    • 2020-08-30
    • 2020-10-25
    • 2019-10-03
    • 2010-12-11
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多