Reputation: 801
How can I count the occurrences of a specific character into a string, with LUA, please?
I give here an example
let the string: "my|fisrt|string|hello"
I want to count how many occurrences of the character "|" has the string. In this case, it should return 3
How can I do it please?
Upvotes: 4
Views: 3373
Reputation: 2205
gsub
returns the number of operations in the second value
local s = "my|fisrt|string|hello"
local _, c = s:gsub("|","")
print(c) -- 3
Upvotes: 6
Reputation: 8718
The most simple solution is just to count it character by character:
local count = 0
local string = "my|fisrt|string|hello"
for i=1, #string do
if string:sub(i, i) == "|" then
count = count + 1
end
end
Alternatively, count all the matches for your character:
local count = 0
local string = "my|fisrt|string|hello"
for i in string:gmatch("|") do
count = count + 1
end
Upvotes: 5