什么方法可以在lua中查找(并循环遍历)一个字符串中所有的子字符串?例如,如果我有一个字符串:
"honewaidoneaeifjoneaowieone"
我希望能够遍历字符串中所有"one"的实例(也就是索引),虽然我可以看到它出现了四次,但我不知道如何找到它们。我知道string.find()可以找到第一个实例,但这并没有什么帮助。
您可以告诉string.find
从哪里开始搜索:
s="honewaidoneaeifjoneaowieone"
p="one"
b=1
while true do
local x,y=string.find(s,p,b,true)
if x==nil then break end
print(x)
b=y+1
end
这段代码在上一个匹配结束后开始每次搜索,也就是说,它只会找到字符串的非重叠出现。如果你想要查找字符串的重叠出现,请使用 b=x+1
。
local str = "honewaidoneaeifjoneaowieone"
-- This one only gives you the substring;
-- it doesn't tell you where it starts or ends
for substring in str:gmatch 'one' do
print(substring)
end
-- This loop tells you where the substrings
-- start and end. You can use these values in
-- string.find to get the matched string.
local first, last = 0
while true do
first, last = str:find("one", first+1)
if not first then break end
print(str:sub(first, last), first, last)
end
-- Same as above, but as a recursive function
-- that takes a callback and calls it on the
-- result so it can be reused more easily
local function find(str, substr, callback, init)
init = init or 1
local first, last = str:find(substr, init)
if first then
callback(str, first, last)
return find(str, substr, callback, last+1)
end
end
find(str, 'one', print)
for index in ("honewaidoneaeifjoneaowieone"):gmatch("()one") do print(index) end
- Egor Skriptunoffaaaa
中搜索子字符串aaa
,我的解决方案效果不佳。让我们等待一个带有“循环内find()”解决方案的答案。 - Egor Skriptunoff