StrCount

From NSIS Wiki
Jump to navigationJump to search
Author: seki (talk, contrib)


Description

Requires: LogicLib header file.

Version: 1.0.

This function returns the number of occurrences of a substring (that can be a single character) in a string.

How To Use

Syntax

${StrCount} String SubString sensitiveness
Pop ResultVar

or

Push String
Push SubString
Push sensitiveness
Call StrCount
Pop ResultVar

Parameters

String
The string where we want to search for SubString.
SubString
Character(s) to find in String, a single char or a substring.
sensitiveness
can be s for a case-sensitive search or anything else for case-insensitive search.
ResultVar
The variable that will get the number of occurrences.

Examples

Push AbABABa
Push Ba
Push "i"
Call StrCount
Pop $0 ;$0=3
${StrCount} abcdefcd c i
Pop $0 ;$0=2

Function Code

!define StrCount "!insertmacro StrCount"
 
!macro StrCount str look si
    Push ${str}
    Push ${look}
    Push ${si}
    Call StrCount
!macroend
 
Function StrCount 
	;takes the following parameters by the stack:
	; case sensitive ('s') or insensitive
    ; string to lookup
    ; string where to search
 
	Exch $2	;Stack = ($2 test str)
    Exch	;Stack = (test $2 str)
    Exch $1	;Stack = ($1 $2 str)
    Exch	;Stack = ($2 $1 str)
    Exch 2	;Stack = (str $1 $2)
    Exch $0	;Stack = ($0 $1 $2)
    Exch 2	;Stack = ($2 $1 $0) just to pop in natural order
    Push $3
    Push $4
    Push $5	
    Push $6	;Stack = ($6 $5 $4 $3 $2 $1 $0)
 
	StrLen $4 $1    
    StrCpy $5 0
    StrCpy $6 0
 
    ;now $0=str, $1=test, $2=s/i, $3=tmp str, $4=lookup len, $5=index, $6=count
 
    loop:
    StrCpy $3 $0 $4 $5
    StrCmp $3 "" end
    ${if} $2 == 's'
    	StrCmpS $3 $1 count ignore
    ${else}
    	StrCmp $3 $1 count ignore
    ${endif}
    count:
    IntOp $6 $6 + 1	;count++
    ignore:
    IntOp $5 $5 + 1 ;index++
	goto loop
	end:
 
    Exch 6	;Stack = ($0 $5 $4 $3 $2 $1 $6)
	Pop $0
    Pop $5
    Pop $4
    Pop $3
    Pop $2
    Pop $1	;Stack = ($6)
    Exch $6	;count is on top stack
FunctionEnd

Versions History

1.0
Initial release.

Credits

Author: Sébastien Kirche (seki).
Wiki page based on StrTok documentation.