Get the index of a character in a string

What I want is to get the index of the second time a character appears in a string, for example:

local str = "Apples are very good!"

Basically, I want to get the second time a space (" ") appears.
This code only gets the first time the designated character appears:

string.find(msg, " ")

Note: Im just saying second because I don’t know how else to word it, basically just make it customizable so I can get the third, or fourth, or fifth and so on time it appears.

theres probably an easier way to do this but this works

local GetIndex = function(Str, Start)
	local Found = 0
	for a,b,c in string.gmatch(Str, "()(%s+)()") do 
		Found += 1 
		
		if (Found >= Start) then 
			return a
		end
	end
end

print(GetIndex("Apples are very good!", 2)) --// 11
1 Like
local function getAllIndexes(s: string, c: string): {number}
	local indexes, index = {}, 0
	while true do 
		index = s:find(c, index+1, true)
		if not index then break end
		table.insert(indexes, index)
	end
	return indexes 
end

--{[1]: 7, [2]: 11, [3]: 16}
print(getAllIndexes("Apples are very good!", " "))
1 Like

If the OP only wants the second character then there is. string.gmatch returns an iterator so you can do a “pre-call” to skip the first find and go to the next.

local str = "Apples are very good!"
local itr = string.gmatch(str, "()(%s+)()")
itr() --first call
print(itr()::any) --second call; prints 11 which is the 2nd space
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.