Tormy Van Cool
Tormy Van Cool

Reputation: 801

LUA: count occurrences of a character into a string?

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

Answers (2)

Mike V.
Mike V.

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

Kelvin Schoofs
Kelvin Schoofs

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

Related Questions