Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Count the number of occurrences in a text string
Parent
Count the number of occurrences in a text string
If I have some text in a cell, how can I find the number of times another piece of text appears in it?
For example, suppose A1
contains Peter Piper picked a peck of pickled peppers.
. pick
occurs 2 times in this string. What formula can I put in A2
so that it counts the occurrences of pick
and returns 2?
Post
@elgonzo mentioned correctly that the nice trick from @pnuts can not be applied if you are interested in the number of occurrences including overlapping ones.
So, just in case someone is in need of such a functionality, here is a function in LibreOffice Basic which handles that case:
Function countOccurrences(searchedWithin As String, searchedFor As String) As Long
Dim count As Long
Dim foundPos As Long
count = -1 ' Will become 0 on loop entry and then 1 if really found the first time
foundPos = 0 ' Will cause search to start at 1 in first loop iteration
Do
count = count + 1
foundPos = Instr(foundPos + 1, searchedWithin, searchedFor, 0)
Loop While foundPos > 0
countOccurrences = count
End Function
2 comment threads