IF - Comparing string length

Microsoft / Dos 6.1
January 26, 2011 at 19:30:53
Specs: Windows 7 Ultimate, 4GB DDR2
Hi, I would like to know if there's a way to compare two variable strings in length? I need to check if a variable has a length less or equal to 2, such as:


SET a=7
SET b=33

IF "%a%" LSS "XY" SET "a=0%a%"
IF "%b%" LSS "XY" SET "b=0%b%"

ECHO %a% %b%


See More: IF - Comparing string length

Report •

January 26, 2011 at 19:37:03
If all you need is to know if there are two or less characters in a variable you can see if a substring expands to nothing:

if not defined var (
    echo Var is empty!
) else if "%var:~2%"=="" (
    echo var contains 2 or less characters
) else echo var contain more than 2 characters

Report •

January 26, 2011 at 19:41:09
I just realized what you are actually doing(leading zeros).

set /a a+=100
set a=%a:~1%

Report •

January 26, 2011 at 19:56:57
Hmm I tried in an almost right way before:

Set a=7
IF "%a:~-2%"=="" SET "a=0%a%"

But this last one seems to do the trick, thanks:

Set a=7
IF "%a:~1%"=="" SET "a=0%a%"

Report •

Related Solutions

Ask Question