0

是否有现有的 NSIS 函数/宏可以告诉我一个字符(或字符串)在字符串中出现的次数?

例如:

${StrCount} "abba" "a" $0
# $0 will equal 2 (because the character 'a' occurs twice)
4

1 回答 1

1

您可以尝试这个同时支持计算单个字符或子字符串以及区分大小写或不区分大小写的函数:

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 not to mess 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

!macro StrCount str look si
    Push ${str}
    Push ${look}
    Push ${si}
    Call StrCount
!macroend
!define StrCount "!insertmacro StrCount"

像这样称呼它:

${StrCount} "AbABABa" "Ba" "i" #or 's' for case sensitive
Pop $0
DetailPrint "count=$0"
于 2013-04-24T09:17:43.013 回答