如何在 Lua 程式設計中分割字串?
分割字串的過程是指我們傳遞一個正則表示式或模式,以此將給定的字串分割為不同的部分。
在 Lua 中,標準庫中沒有分割函式,但我們可以利用其他函式來做通常分割函式會完成的工作。
Lua 中一個非常簡單的分割函式示例是使用 **gmatch()** 函式,然後傳遞一個我們要根據其分割字串的模式。
示例
考慮以下示例 −
local example = "lua is great" for i in string.gmatch(example, "%S+") do print(i) end
輸出
lua is great
上述示例對於簡單的模式來說很好用,但是當我們想要使用正則表示式以及我們可能具有一個用於分割的預設模式的情況時,我們可以考慮一個更優雅的示例。
示例
考慮以下示例 −
function mysplit (inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
ans = mysplit("hey bro whats up?")
for _, v in ipairs(ans) do print(v) end
ans = mysplit("x,y,z,m,n",",")
for _, v in ipairs(ans) do print(v) end輸出
hey bro whats up? x y z m n
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP