T3RRYT3RR0R

StrLen Macro

Apr 4th, 2021 (edited)
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 2.08 KB | None | 0 0
  1. @Echo off
  2.  
  3. :# Macro escaped for definition with delayed expansion enabled.
  4.  
  5.  Setlocal EnableDelayedExpansion
  6.  
  7. ===================================================================:# [StrLen]
  8. :# %[StrLen]% Returnvar Var
  9. :# Source: https://www.dostips.com/forum/memberlist.php?mode=viewprofile&u=417
  10.  
  11. :# Returns two results:
  12. :#  Returnvar=ActualLength
  13. :#  ReturnVar[0i]=ActualLenght-1
  14. :# use Zero indexed suffix '[0i]' when iterating over a string from first character to last IE:
  15. :# For /L %%i in (0 1 !Returnvar[0i]!)Do For /F "Delims=" %%c in ('Set /a %%i + 1')Do Echo(Character %%c = !Variable:~%%i,1!
  16.  
  17. (Set \n=^^^
  18.  
  19. %= \n macro newline variable - Do not Modify =%)
  20.  
  21.  Set [StrLen]=for /L %%n in (1 1 2) do if %%n==2 (%\n%
  22.   For /F "tokens=1,* delims=, " %%G in ("^!argv^!")Do (%\n%
  23.    Set "[StrLen]tmpStr=^!%%~H^!"%\n%
  24.    Set "[StrLen]Len=0"%\n%
  25.    Set "[StrLen]Result=%%~G"%\n%
  26.    If not "^![StrLen]tmpStr^!" == "" For %%N IN (4096 2048 1024 512 256 128 64 32 16 8 4 2 1)Do (%\n%
  27.     If not "^![StrLen]tmpStr:~%%N,1^!" == "" (%\n%
  28.       Set /A "[StrLen]Len += %%N"%\n%
  29.       Set "[StrLen]tmpStr=^![StrLen]tmpStr:~%%N^!"%\n%
  30.    ))%\n%
  31.   )%\n%
  32.   Set /A "^![StrLen]Result^!=^![StrLen]Len^! + 1,^![StrLen]Result^![0i]= ^![StrLen]Len^!"%\n%
  33.   If "^![StrLen]tmpStr^!" == "" Set /A "^![StrLen]Result^!=0,^![StrLen]Result^![0i]=0"%\n%
  34.  )Else set argv=,
  35.  
  36. ===============================================================:# End [StrLen]
  37.  
  38. :# Usage examples.
  39.  
  40. :# Example one: test using parameters from the command line using parameters
  41.  If not "%~2" == "" (
  42.   %[strLen]% "%~1" "%~2"
  43.   If /I "%~3" == "/O" Echo(%~1=!%~1!
  44.    For /F "tokens=1,2 Delims=;" %%G in ("!%~1!;!%~1[0i]!")Do Endlocal & (
  45.    Set /A "%~1=%%~G,%~1[0i]=%%~H"
  46.   )
  47.   Exit /B 0
  48.  )Else if not "%~1" == "" (
  49.   Echo(%~n0 ReturnVar VariableName
  50.   Exit /b 0
  51.  )
  52.  
  53. :# Example two: Example use with computername variable.
  54.  %[Strlen]% CN Computername
  55.  Echo(Computername "%Computername%" contains !CN! characters:
  56.  For /L %%i in (0 1 !CN[0i]!)Do For /F "Delims=" %%c in ('Set /a %%i + 1')Do Echo(Character %%c = !ComputerName:~%%i,1!
Add Comment
Please, Sign In to add comment