Jump to content

Count occurrences of a substring: Difference between revisions

(Added Kotlin)
Line 1,291:
 
=={{header|Lua}}==
Solution 1:
<lang Lua>function countSubstring (s1, s2)
 
<lang Lua>function countSubstring (s1, s2)
return select(2, s1:gsub(s2, ""))
end
 
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</lang>
<pre>3
2</pre>
 
 
Solution 2:
 
<lang Lua>function countSubstring(s1, s2)
local count = 0
for eachMatch in s1:gmatch(s2) do count = count + 1 end
count = count + 1
end
return count
end
 
print(countSubstring("the three truths", "th"))
print(countSubstring("ababababab", "abab"))</lang>
<pre>3
2</pre>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.