Dual purpose "CountString() "

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Randy Walker
Addict
Addict
Posts: 998
Joined: Sun Jul 25, 2004 4:21 pm
Location: USoA

Dual purpose "CountString() "

Post by Randy Walker »

Searched for similar thought but nothing quite like this turned up. We all know CountString() is great for returning occurrences. How useful would it be if it could also be used to return placement,similar to the FindString() function?

PROPOSED SYNTAX WOULD ADD OPTIONAL PARAMETER:
Result = CountString(String$, StringToCount$ [,Occurrence])


EXAMPLE (current design):
s$ = "word1,word2,word3,word4,word5"
Result = CountString(s$, "d")
Debug Result
5

EXAMPLE (new optional parameter):
s$ = "word1,word2,word3,word4,word5"
Result = CountString(s$, "d", 4)
Debug Result
22

GIves us 22 because that is the position of the 4th "d".
- - - - - - - - - - - - - - - -
Randy
I *never* claimed to be a programmer.
User avatar
kenmo
Addict
Addict
Posts: 2033
Joined: Tue Dec 23, 2003 3:54 am

Re: Dual purpose "CountString() "

Post by kenmo »

That would be handy, although I think it makes more sense as
a new function (such as FindOccurrence)
or a flag for FindString (since it returns a position)
instead of a flag for CountString (which should return a count, of course).

If anyone wants it, here is one simple implementation:

Code: Select all

Procedure.i FindOccurrence(String.s, StringToFind.s, Occurrence.i = 1, Mode.i = #PB_String_CaseSensitive)
  If (String And StringToFind And Occurrence > 0)
    Protected Start.i = 1
    Protected Found.i = 0
    Protected Pos.i
    While (Found < Occurrence)
      Pos = FindString(String, StringToFind, Start, Mode)
      If (Pos)
        Found + 1
        If (Found = Occurrence)
          ProcedureReturn (Pos)
        Else
          Start = Pos + Len(StringToFind)
        EndIf
      Else
        Break
      EndIf
    Wend
  EndIf
  ProcedureReturn (0)
EndProcedure

Debug Str(CountString("word1,word2,word3,word4,word5", "d")) + " (count)"

Debug FindOccurrence("word1,word2,word3,word4,word5", "d")
Debug FindOccurrence("word1,word2,word3,word4,word5", "d", 4)
Debug FindOccurrence("word1,word2,word3,word4,word5", "z")

Debug FindOccurrence("aaaAAAaaa", "aaa", 2)
Debug FindOccurrence("aaaAAAaaa", "aaa", 2, #PB_String_NoCase)
Little John
Addict
Addict
Posts: 4779
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Dual purpose "CountString() "

Post by Little John »

kenmo wrote:I think it makes more sense as
a new function (such as FindOccurrence)
or a flag for FindString (since it returns a position)
instead of a flag for CountString (which should return a count, of course).
Yep.
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: Dual purpose "CountString() "

Post by davido »

@kenmo,
Thank you.
I'll find this useful. :D
DE AA EB
Post Reply