How to get string length (two possibilites)
Posted: 28 Jun 2010 05:09
Hi all,
here are two possibilites to determine the string's length. I hope you like them.
First version sets a temporary variable and when it becomes undefined the counter determines the string's length. Of course string is passed as %1 (first parameter).
Second version sets a temporary variable character by character and when it becomes the same as source string we know the string's length. Of course string is passed as %1 (first parameter). This version does not handle special characters (" etc.).
Saso
here are two possibilites to determine the string's length. I hope you like them.
First version sets a temporary variable and when it becomes undefined the counter determines the string's length. Of course string is passed as %1 (first parameter).
Code: Select all
@echo off
set strorg=%~1
set strtmp=
set /a cnt=0
:1
call set strtmp=%%strorg:~%cnt%,1%%
if defined strtmp set /a cnt=cnt+1&&goto :1
echo String length is %cnt%
Second version sets a temporary variable character by character and when it becomes the same as source string we know the string's length. Of course string is passed as %1 (first parameter). This version does not handle special characters (" etc.).
Code: Select all
@echo off
set strorg=%~1
set strtmp=
set /a cnt=0
:0
call set strtmp=%strtmp%%%strorg:~%cnt%,1%%
if not "[%strorg%]"=="[%strtmp%]" set /a cnt=cnt+1&&goto :0
set /a strlen=cnt+1
echo String length is %strlen%
Saso