StrTok function

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


Description

Here's a StrTok function which works most like the 'c' strtok function. First push the string that needs tokenizing; then push the token string, call the func, and get the first part back from stack, with the remains of the initial string also still on stack, ready for the next call.

Example of Usage

Push "version 1.24"
Push " ."
Call StrTok
Pop $R0 ; R0 now contains 'version'
Pop $R1 ; R1 is now '1.24'; popping just for demo purposes
Push $R1 ; continue parsing the same string
Push " ."
Call StrTok
Pop $R0 ; R0 now contains '1'
Push " ."
Call StrTok
Pop $R0 ; R0 now contains '24'
Pop $R1 ; should be empty string now, this just to clean the stack

The Function

Here's the source of the function:

;author bigmac666
Function StrTok
  Exch $R1
  Exch 1
  Exch $R0
  Push $R2
  Push $R3
  Push $R4
  Push $R5
 
  ;R0 fullstring
  ;R1 tokens
  ;R2 len of fullstring
  ;R3 len of tokens
  ;R4 char from string
  ;R5 testchar
 
  StrLen $R2 $R0
  IntOp $R2 $R2 + 1
 
  loop1:
    IntOp $R2 $R2 - 1
    IntCmp $R2 0 exit
 
    StrCpy $R4 $R0 1 -$R2
 
    StrLen $R3 $R1
    IntOp $R3 $R3 + 1
 
    loop2:
      IntOp $R3 $R3 - 1
      IntCmp $R3 0 loop1
 
      StrCpy $R5 $R1 1 -$R3
 
      StrCmp $R4 $R5 Found
    Goto loop2
  Goto loop1
 
  exit:
  ;Not found!!!
  StrCpy $R1 ""
  StrCpy $R0 ""
  Goto Cleanup
 
  Found:
  StrLen $R3 $R0
  IntOp $R3 $R3 - $R2
  StrCpy $R1 $R0 $R3
 
  IntOp $R2 $R2 - 1
  IntOp $R3 $R3 + 1
  StrCpy $R0 $R0 $R2 $R3
 
  Cleanup:
  Pop $R5
  Pop $R4
  Pop $R3
  Pop $R2
  Exch $R0
  Exch 1
  Exch $R1
 
FunctionEnd

Questions/comments/bugs/fixes? Send a private message. Enjoy,

bigmac666