Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting number of string occurrences

Tags:

lua

I'm trying to count the number of times that " --" occurs in a string.

So for instance, it occurs twice here 'a --b --c'

I tried the following, but it gives me 4 instead of 2, any idea why?

argv='a --b --c'
count = 0
for i in string.gfind(argv, " --") do
   count = count + 1
end
print(count)
like image 838
Yaroslav Bulatov Avatar asked Jun 22 '12 07:06

Yaroslav Bulatov


People also ask

How do you count occurrences of a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count the number of occurrences of a character in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

How do you count the number of times an element appears in a string?

Python String count() Method Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string.

How do you count occurrences of a string in Python?

Python String count() MethodThe count() method searches (case-sensitive) the specified substring in the given string and returns an integer indicating occurrences of the substring. By default, the counting begins from 0 index till the end of the string.


2 Answers

you can actually do this as a one-liner using string.gsub:

local _, count = string.gsub(argv, " %-%-", "")
print(count)

no looping required!

Not recommended for large inputs, because the function returns the processed input to the _ variable, and will hold onto the memory until the variable is destroyed.

like image 50
Mike Corcoran Avatar answered Oct 25 '22 09:10

Mike Corcoran


This snippet could be helpful, based on response of Mike Corcoran & optimisation suggestion of WD40

function count(base, pattern)
    return select(2, string.gsub(base, pattern, ""))
end

print(count('Hello World', 'l'))
like image 34
Abhishek Kumar Avatar answered Oct 25 '22 10:10

Abhishek Kumar