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)
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.
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.
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.
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.
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With