IdeasVacuum wrote:Looks like breeze4me has the fastest code. It also works with characters outside the ASCII range.
Checked the search for the LF character by copying 20,000 lines to the clipboard. My code executed in 207-210 ms, and the code from the author of breeze4me completed in 240-250 ms.
Code: Select all
EnableExplicit
#SOC=SizeOf(Character)
Procedure CountStr(text$)
Protected c=1, *old.Character=@text$
; text$ = RTrim( LTrim(text$, #LF$), #LF$)
While *old\c
If *old\c=10 ; LF
c+1
EndIf
*old+#SOC
Wend
ProcedureReturn c
EndProcedure
; Debug CountStr(GetClipboardText())
Procedure StrToArrLetter(Array Arr.c(1), String$)
Protected LenStr, i
LenStr = Len(String$)
If LenStr
ReDim Arr(LenStr - 1)
PokeS(Arr(), String$, -1, #PB_String_NoZero)
EndIf
ProcedureReturn
EndProcedure
Procedure CountStr1(String$)
Protected c, i
Protected Dim Arr.c(0)
StrToArrLetter(Arr(), String$)
c=1
For i=0 To ArraySize(Arr())
If Arr(i) = 10
c+1
EndIf
Next
ProcedureReturn c
EndProcedure
Define Count, StartTime, Time.s
StartTime=ElapsedMilliseconds()
Count = CountStr(GetClipboardText())
Time = "Time = " + Str(ElapsedMilliseconds()-StartTime) + " ms"
; Debug GetClipboardText()
Debug Time
Debug Count
; это жутко медленно, 14 сек для 20000 строк, против мгновения в предыдущих примерах
Procedure CountStr2(str$)
Protected Pos=0, c
str$ = RTrim( LTrim(str$, #LF$), #LF$)
c=0
Repeat
c+1
Pos = FindString(str$, #LF$, Pos+1)
Until Not Pos
ProcedureReturn c
EndProcedure