82

There doesn't appear to be an easy way to get the length of a string in a batch file. E.g.,

SET MY_STRING=abcdefg
SET /A MY_STRING_LEN=???

How would I find the string length of MY_STRING?

Bonus points if the string length function handles all possible characters in strings including escape characters, like this: !%^^()^!.

1

20 Answers 20

100

As there is no built in function for string length, you can write your own function like this one:

@echo off
setlocal
REM *** Some tests, to check the functionality ***
REM *** An emptyStr has the length 0
set "emptyString="
call :strlen result emptyString
echo %result%

REM *** This string has the length 14
set "myString=abcdef!%%^^()^!"
call :strlen result myString
echo %result%

REM *** This string has the maximum length of 8191
setlocal EnableDelayedExpansion
set "long=."
FOR /L %%n in (1 1 13) DO set "long=!long:~-4000!!long:~-4000!"
(set^ longString=!long!!long:~-191!)

call :strlen result longString
echo %result%

goto :eof

REM ********* function *****************************
:strlen <resultVar> <stringVar>
(   
    setlocal EnableDelayedExpansion
    (set^ tmp=!%~2!)
    if defined tmp (
        set "len=1"
        for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
            if "!tmp:~%%P,1!" NEQ "" ( 
                set /a "len+=%%P"
                set "tmp=!tmp:~%%P!"
            )
        )
    ) ELSE (
        set len=0
    )
)
( 
    endlocal
    set "%~1=%len%"
    exit /b
)

This function needs always 13 loops, instead of a simple strlen function which needs strlen-loops.
It handles all characters.

The strange expression (set^ tmp=!%~2!) is necessary to handle ultra long strings, else it's not possible to copy them.

7
  • 1
    Maybe the exclamation points are causing problems because delayed expansion is enabled before the string is set to begin with.
    – jpmc26
    Commented May 11, 2013 at 3:59
  • 1
    For anyone who is wondering: this method fails when string is longer than 8186 on windows 7. Microsoft states that string can be at most 8191 characters long
    – MaLiN2223
    Commented Apr 25, 2018 at 10:20
  • @MaLiN2223 I fxied the code, now it can handle strings up to 8191 characters
    – jeb
    Commented Aug 22, 2019 at 18:55
  • 1
    Unless theres another version, the above StrLen function currently misses % in strings and returns an inaccurate count. I've tested the suggested modification with all characters and it returns a more accurate count, But I'll take the time to read throught the link and explore the issues surrounding long strings. One of the strings I tested the function with that failed to pick up %: Set "test=whatever you / ? > want it to {} ][ be! @ # $ % ^ & * ~ v;_ + = | ( \ ) "" >< 80"
    – T3RR0R
    Commented Jan 31, 2020 at 20:30
  • 1
    @T3RR0R No you'r wrong. Please let's discuss this in the chat
    – jeb
    Commented Jan 31, 2020 at 20:34
41

You can do it in two lines, fully in a batch file, by writing the string to a file and then getting the length of the file. You just have to subtract two bytes to account for the automatic CR+LF added to the end.

Let's say your string is in a variable called strvar:

ECHO %strvar%> tempfile.txt
FOR %%? IN (tempfile.txt) DO ( SET /A strlength=%%~z? - 2 )

The length of the string is now in a variable called strlength.

In slightly more detail:

  • FOR %%? IN (filename) DO ( ... : gets info about a file
  • SET /A [variable]=[expression] : evaluate the expression numerically
  • %%~z? : Special expression to get the length of the file

To mash the whole command in one line:

ECHO %strvar%>x&FOR %%? IN (x) DO SET /A strlength=%%~z? - 2&del x
6
  • 2
    You should change this to >x ECHO.%strvar% instead of ECHO %strvar%>x, otherwise it fails on inputs like 2 or 3 Commented Feb 26, 2016 at 23:13
  • 3
    I don't want to be a hater but it's nice to delete temp files that you create after your are done. That is the point on temp files xD. del tempfile.txt
    – IGRACH
    Commented Mar 19, 2016 at 21:23
  • 3
    This method is extremely simple in concept, and also one of the fastest known methods. But I don't use it as a general purpose batch routine because ideally the routine should guarantee that the temp file full path is unique across all processes - not a trivial undertaking. You don't want the routine to fail because two processes attempt to use the same file name at the same time. I also agree that the temp file should be deleted when finished.
    – dbenham
    Commented Dec 3, 2016 at 15:37
  • 2
    This code has several problems. First using %strvar% is not good. Why? Try the code with set strvar=2 or with set "strvar=Redirection operators are < and > and >> and |". Next creating a file is slower than doing all in memory and is not good for SSD disks. The result is also wrong if the current working directory is write-protected for the user account using this batch code as the file can't be created in current directory. The result is also wrong if tempfile.txt exists in current directory, but has read-only attribute set.
    – Mofi
    Commented Dec 16, 2016 at 7:58
  • @Mofi lol those situations are unusual. You could check if the directory is writable using for statement (see here). You could also check if a file with such name already exists in the current directory, and add an alternate filename by adding a few codes.
    – amegyoushi
    Commented Apr 30, 2019 at 16:05
24

I prefer jeb's accepted answer - it is the fastest known solution and the one I use in my own scripts. (Actually there are a few additional optimizations bandied about on DosTips, but I don't think they are worth it)

But it is fun to come up with new efficient algorithms. Here is a new algorithm that uses the FINDSTR /O option:

@echo off
setlocal
set "test=Hello world!"

:: Echo the length of TEST
call :strLen test

:: Store the length of TEST in LEN
call :strLen test len
echo len=%len%
exit /b

:strLen  strVar  [rtnVar]
setlocal disableDelayedExpansion
set len=0
if defined %~1 for /f "delims=:" %%N in (
  '"(cmd /v:on /c echo(!%~1!&echo()|findstr /o ^^"'
) do set /a "len=%%N-3"
endlocal & if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b

The code subtracts 3 because the parser juggles the command and adds a space before CMD /V /C executes it. It can be prevented by using (echo(!%~1!^^^).


For those that want the absolute fastest performance possible, jeb's answer can be adopted for use as a batch "macro" with arguments. This is an advanced batch technique devloped over at DosTips that eliminates the inherently slow process of CALLing a :subroutine. You can get more background on the concepts behind batch macros here, but that link uses a more primitive, less desirable syntax.

Below is an optimized @strLen macro, with examples showing differences between the macro and :subroutine usage, as well as differences in performance.

@echo off
setlocal disableDelayedExpansion

:: -------- Begin macro definitions ----------
set ^"LF=^
%= This creates a variable containing a single linefeed (0x0A) character =%
^"
:: Define %\n% to effectively issue a newline with line continuation
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

:: @strLen  StrVar  [RtnVar]
::
::   Computes the length of string in variable StrVar
::   and stores the result in variable RtnVar.
::   If RtnVar is is not specified, then prints the length to stdout.
::
set @strLen=for %%. in (1 2) do if %%.==2 (%\n%
  for /f "tokens=1,2 delims=, " %%1 in ("!argv!") do ( endlocal%\n%
    set "s=A!%%~1!"%\n%
    set "len=0"%\n%
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (%\n%
      if "!s:~%%P,1!" neq "" (%\n%
        set /a "len+=%%P"%\n%
        set "s=!s:~%%P!"%\n%
      )%\n%
    )%\n%
    for %%V in (!len!) do endlocal^&if "%%~2" neq "" (set "%%~2=%%V") else echo %%V%\n%
  )%\n%
) else setlocal enableDelayedExpansion^&setlocal^&set argv=,

:: -------- End macro definitions ----------

:: Print out definition of macro
set @strLen

:: Demonstrate usage

set "testString=this has a length of 23"

echo(
echo Testing %%@strLen%% testString
%@strLen% testString

echo(
echo Testing call :strLen testString
call :strLen testString

echo(
echo Testing %%@strLen%% testString rtn
set "rtn="
%@strLen% testString rtn
echo rtn=%rtn%

echo(
echo Testing call :strLen testString rtn
set "rtn="
call :strLen testString rtn
echo rtn=%rtn%

echo(
echo Measuring %%@strLen%% time:
set "t0=%time%"
for /l %%N in (1 1 1000) do %@strlen% testString testLength
set "t1=%time%"
call :printTime

echo(
echo Measuring CALL :strLen time:
set "t0=%time%"
for /l %%N in (1 1 1000) do call :strLen testString testLength
set "t1=%time%"
call :printTime
exit /b


:strlen  StrVar  [RtnVar]
::
:: Computes the length of string in variable StrVar
:: and stores the result in variable RtnVar.
:: If RtnVar is is not specified, then prints the length to stdout.
::
(
  setlocal EnableDelayedExpansion
  set "s=A!%~1!"
  set "len=0"
  for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if "!s:~%%P,1!" neq "" (
      set /a "len+=%%P"
      set "s=!s:~%%P!"
    )
  )
)
(
  endlocal
  if "%~2" equ "" (echo %len%) else set "%~2=%len%"
  exit /b
)

:printTime
setlocal
for /f "tokens=1-4 delims=:.," %%a in ("%t0: =0%") do set /a "t0=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100
for /f "tokens=1-4 delims=:.," %%a in ("%t1: =0%") do set /a "t1=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100
set /a tm=t1-t0
if %tm% lss 0 set /a tm+=24*60*60*100
echo %tm:~0,-2%.%tm:~-2% msec
exit /b

-- Sample Output --

@strLen=for %. in (1 2) do if %.==2 (
  for /f "tokens=1,2 delims=, " %1 in ("!argv!") do ( endlocal
    set "s=A!%~1!"
    set "len=0"
    for %P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
      if "!s:~%P,1!" neq "" (
        set /a "len+=%P"
        set "s=!s:~%P!"
      )
    )
    for %V in (!len!) do endlocal&if "%~2" neq "" (set "%~2=%V") else echo %V
  )
) else setlocal enableDelayedExpansion&setlocal&set argv=,

Testing %@strLen% testString
23

Testing call :strLen testString
23

Testing %@strLen% testString rtn
rtn=23

Testing call :strLen testString rtn
rtn=23

Measuring %@strLen% time:
1.93 msec

Measuring CALL :strLen time:
7.08 msec
5
  • 2
    K+1 for an interesting approach. I would add 'skip=1' and 'echo(!%~1!'. You need to subtract 3, as the echo appends here always a space at the end of each line (caused by the pipe?)
    – jeb
    Commented Dec 18, 2012 at 7:24
  • @jeb - good catch with echo( - the method now properly handles a string containing only white space. There is no need for SKIP, the last SET wins. I don't see much benefit to SKIP since there may be multiple line feeds in the original string. You are correct about the space. I came up with syntax that avoids the space, but didn't bother incorporating it in code. See revised answer.
    – dbenham
    Commented Dec 18, 2012 at 12:46
  • That's a nice answer, almost a one-liner. I use it but changed it to accept the line as direct input instead of a variable name and return the length as the error level (i.e. exit /b %len%).
    – Jay
    Commented Nov 14, 2016 at 16:56
  • 2
    @Jay - The reason I use a variable instead of a string literal is because there are many literal strings that cannot be passed as a parameter, but a variable can hold all possible batch strings.
    – dbenham
    Commented Dec 8, 2016 at 13:25
  • @dbenham True... I didn't think of that part. I will most probably revert back to use a variable. Thanks for the input!
    – Jay
    Commented Dec 9, 2016 at 14:31
12

The first few lines are simply to demonstrate the :strLen function.

@echo off
set "strToMeasure=This is a string"
call :strLen strToMeasure strlen
echo.String is %strlen% characters long
exit /b

:strLen
setlocal enabledelayedexpansion
:strLen_Loop
  if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof

Of course, this is not quite as efficient at the "13 loop" version provided by jeb. But it is easier to understand, and your 3GHz computer can slip through a few thousand iterations in a small fraction of a second.

1
  • Wow - this is a really good and easy solution! Commented Dec 6, 2023 at 9:02
10

Just found ULTIMATE solution:

set "MYSTRING=abcdef!%%^^()^!"
(echo "%MYSTRING%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%-5
echo string "%MYSTRING%" length = %STRLENGTH%

The output is:

string "abcdef!%^^()^!" length = 14

It handles escape characters, an order of magnitude simpler then most solutions above, and contains no loops, magic numbers, DelayedExpansion, temp files, etc.

In case usage outside batch script (mean putting commands to console manually), replace %%RESULT%% key with %RESULT%.

If needed, %ERRORLEVEL% variable could be set to FALSE using any NOP command, e.g. echo. >nul

2
  • It fails with set "myString=&"^&" (Three characters). You could get it working for this string, but it will not work at all with newlines in the content of mystring. Btw. It's slow as it creates multiple new cmd.exe instances
    – jeb
    Commented Feb 12, 2017 at 16:51
  • it also turned out, that in case of error 'Too many arguments in command line' command 'more' should be used with '/e' flag. Commented Jun 3, 2018 at 8:52
5

Yes, of course there's an easy way, using vbscript (or powershell).

WScript.Echo Len( WScript.Arguments(0) )

save this as strlen.vbs and on command line

c:\test> cscript //nologo strlen.vbs "abcd"

Use a for loop to capture the result ( or use vbscript entirely for your scripting task)

Certainly beats having to create cumbersome workarounds using batch and there's no excuse not to use it since vbscript is available with each Windows distribution ( and powershell in later).

6
  • 2
    WSH can be locked down with group policies, though.
    – Joey
    Commented Apr 30, 2011 at 15:34
  • 5
    So can cmd.exe if you are talking about security concerns.
    – ghostdog74
    Commented Apr 30, 2011 at 15:42
  • 4
    There is a very good reason to use jeb's optimized batch solution instead of the VBS solution. The VBS solution is nearly 3 times slower because of the overhead of initializing VBS. But I agree the VBS solution is seductively simple.
    – dbenham
    Commented Jun 22, 2012 at 2:40
  • @dbenham - unless you are doing many thousands of iterations or dealing with extraordinarily slow hardware, speed in this task is hardly an issue. It's not like this is trying to conserve time-slice on a mainframe system. Generally speaking I'd pick the one that is easiest to understand and maintain going forward for anyone that has to open and know the code.
    – RLH
    Commented Dec 27, 2013 at 0:43
  • @RobHuston - I frequently write batch scripts that do need to process thousands of lines in a loop, so a relatively slow strlen function can become significant and is something I try to avoid. Once I have a working fast strlen function, I don't see what there is to maintain. It becomes trivial to reuse in multiple scripts. But this is just my preference. I never said there are no advantages to the VBScript solution. It just depends on what your priorities are.
    – dbenham
    Commented Dec 27, 2013 at 2:33
4

If you are on Windows Vista +, then try this Powershell method:

For /F %%L in ('Powershell $Env:MY_STRING.Length') do (
    Set MY_STRING_LEN=%%L
)

or alternatively:

Powershell $Env:MY_STRING.Length > %Temp%\TmpFile.txt
Set /p MY_STRING_LEN = < %Temp%\TmpFile.txt
Del %Temp%\TmpFile.txt

I'm on Windows 7 x64 and this is working for me.

1
  • Your first sample fails,as FOR parameters only accept one character
    – jeb
    Commented Mar 5, 2014 at 8:34
3

If you insist on having this trivial function in pure batch I suggest this:

@echo off

set x=somestring
set n=0
set m=255

:loop
if "!x:~%m%,1!" == "" (
    set /a "m>>=1"
    goto loop
) else (
    set /a n+=%m%+1
    set x=!x:~%m%!
    set x=!x:~1!
    if not "!x!" == "" goto loop
)

echo %n%

PS. You must have delayed variable expansion enabled to run this.

EDIT. Now I have made an improved version:

@echo off

set x=somestring
set n=0

for %%m in (4095 2047 1023 511 255 127 63 31 15 7 3 1 0) do (
    if not "!x:~%%m,1!" == "" (
        set /a n+=%%m+1
        set x=!x:~%%m!
        set x=!x:~1!
        if "!x!" == "" goto done
    )
)

:done
echo %n%

EDIT2. If you have a C compiler or something on your system you can create the programs you need and miss on the fly if they don't exist. This method is very general. Take string length as an example:

@echo off

set x=somestring

if exist strlen.exe goto comp
echo #include "string.h" > strlen.c
echo int main(int argc, char* argv[]) { return strlen(argv[1]); } >> strlen.c
CL strlen.c 

:comp
strlen "%x%"
set n=%errorlevel%
echo %n%

You have to set up PATH, INCLUDE and LIB appropriately. This too can be done on the fly from the batch script. Even if you don't know whether you've got a compiler or don't know where it is you can search for it in your script.

12
  • endless loop; please recheck.
    – Stephan
    Commented Dec 11, 2019 at 19:54
  • @Stephan It runs fine on my computer. What's wrong?
    – Henrik4
    Commented Dec 11, 2019 at 20:07
  • As I said, it runs in an endless loop. %m%doesn't change.
    – Stephan
    Commented Dec 11, 2019 at 20:18
  • 2
    Found it. You forgot setlocal enabledelayedexpansion
    – Stephan
    Commented Dec 11, 2019 at 20:18
  • @Henrik4 Some drawbacks: Currently the string itself will be destroyed, and your code would be faster for long strings when you increase m to 4095. But it's still slow, as goto :label is a slow operation
    – jeb
    Commented Dec 11, 2019 at 20:37
2

I like the two line approach of jmh_gr.

It won't work with single digit numbers unless you put () around the portion of the command before the redirect. since 1> is a special command "Echo is On" will be redirected to the file.

This example should take care of single digit numbers but not the other special characters such as < that may be in the string.

(ECHO %strvar%)> tempfile.txt
3
  • 1
    But this does not solve the problem for content like: <empty var>, ON, OFF or /?. Or try it with set strvar=^&"&
    – jeb
    Commented Sep 19, 2012 at 6:12
  • @jeb (ECHO "%strvar%")> tempfile.txt should work for all. your last example set... does not work even in your script (double quote inside). And I think with quotes we don not even need () anymore.
    – Mat M
    Commented Sep 24, 2012 at 23:31
  • The sample will work, as delayed expansion is not affected by special characters. And quoting the "%strvar%" can't help for the content &"&
    – jeb
    Commented Sep 25, 2012 at 6:54
1

Just another batch script to calculate the length of a string, in just a few lines. It may not be the fastest, but it's pretty small. The subroutine ":len" returns the length in the second parameter. The first parameter is the actual string being analysed. Please note - special characters must be escaped, that is the case with any string in the batch file.

@echo off
setlocal
call :len "Sample text" a
echo The string has %a% characters.
endlocal
goto :eof

:len <string> <length_variable> - note: string must be quoted because it may have spaces
setlocal enabledelayedexpansion&set l=0&set str=%~1
:len_loop
set x=!str:~%l%,1!&if not defined x (endlocal&set "%~2=%l%"&goto :eof)
set /a l=%l%+1&goto :len_loop
1
@echo off & setlocal EnableDelayedExpansion
set Var=finding the length of strings
for /l %%A in (0,1,10000) do if not "%Var%"=="!Var:~0,%%A!" (set /a Length+=1) else (echo !Length! & pause & exit /b)

set the var to whatever you want to find the length of it or change it to set /p var= so that the user inputs it. Putting this here for future reference.

1
  • Very simple idea :) but takes some time for long strings. Also, 10000 can be changed to 8191 because batch variable's length limit is 8191.
    – user6250760
    Commented Sep 17, 2017 at 2:34
1

I made this simple function to find the length of string

for /l %%a in (0,1,10000) do if not "!text:~%%a,1!" == "" set/a text_len=!text_len!+1

You need to make sure that both !text! and !text_len! variables are defined first

1

Most of the times length is used to get the substring from a string. In that case following approach can be used with NO NEED to use LENGTH FUNCTION.

Examples :

@echo off
set MY_STRING=1234567890

REM Exclude first 2 characters but return rest of the string. 
echo %MY_STRING:~2%
REM outcome :34567890

REM exclude last 2 charter but get rest of the string
echo %MY_STRING:~0,-2%
REM outcome: 123456789

REM Get 2 characters starting at position 3
echo %MY_STRING:~2,2%
REM outcome :34

Syntax : %Variable:~offset, length%

If the length is not specified, then it defaults to the remainder of the variable value.
If either number (offset or length) is negative, then the number used is the length of the environment variable value added to the offset or length specified.

For more details type Help set

0
@echo off
::   warning doesn't like * ( in mystring

setlocal enabledelayedexpansion 

set mystring=this is my string to be counted forty one

call :getsize %mystring%
echo count=%count% of "%mystring%" 

set mystring=this is my string to be counted

call :getsize %mystring%

echo count=%count% of "%mystring%" 

set mystring=this is my string
call :getsize %mystring%

echo count=%count% of "%mystring%" 
echo.
pause
goto :eof

:: Get length of mystring line ######### subroutine getsize ########

:getsize

set count=0

for /l %%n in (0,1,2000) do (

    set chars=

    set chars=!mystring:~%%n!

    if defined chars set /a count+=1
)
goto :eof

:: ############## end of subroutine getsize ########################
1
  • 1
    This works only up to 2000 characters (a batch variable can hold up to 8191 characters) and it's extremly slow, as it loop always 2000 times independent of the string length
    – jeb
    Commented Apr 14, 2015 at 10:53
0

I want to preface this by saying I don't know much about writing code/script/etc. but thought I'd share a solution I seem to have come up with. Most of the responses here kinda went over my head, so I was curious to know if what I've written is comparable.

@echo off

set stringLength=0

call:stringEater "It counts most characters"
echo %stringLength%
echo.&pause&goto:eof

:stringEater
set var=%~1
:subString
set n=%var:~0,1%
if "%n%"=="" (
        goto:eof
    ) else if "%n%"==" " (
        set /a stringLength=%stringLength%+1
    ) else (
        set /a stringLength=%stringLength%+1
    )
set var=%var:~1,1000%
if "%var%"=="" (
        goto:eof
    ) else (
        goto subString
    )

goto:eof
1
  • Sorry, but your solution is incredible slow, as you need as many iterations as characters are there. The construct if "%n%"=="" will fail when the string contains a quote. Btw. the else if/else construct is superflous, as you already know that there must be a character. The set b=%var:~0,1% will fail for any special charcater in the string |<>&
    – jeb
    Commented Jan 10, 2017 at 12:04
0

It's Much Simplier!

Pure batch solution. No temp files. No long scripts.

@echo off
setlocal enabledelayedexpansion
set String=abcde12345

for /L %%x in (1,1,1000) do ( if "!String:~%%x!"=="" set Lenght=%%x & goto Result )

:Result 
echo Lenght: !Lenght!

1000 is the maximum estimated string lenght. Change it based on your needs.

1
  • Your solution is more or less the same as the one of @eddie Duncan-Dunlop. It's easy but slow
    – jeb
    Commented Dec 4, 2018 at 16:38
0

I know its a little late - like 10 years, but what I do for this is to write a C# Console app called strlen call it and then use the errorlevel to get the returned length

0

This works too. Also its simple and easy to understand.

setlocal
set strcopy=thisismystring
set count=0
:testremovecount
if "%strcopy%"=="" goto done
set strcopy=%strcopy:~1%
set count=%count%+1
goto testremovecount
:done
endlocal

set "strcopy" to your string

output is "count"

The most complicated part is

set strcopy=%strcopy:~1%

The "%strcopy:~1%" part if this line removes only the first character from the string variable "strcopy". for more info see https://www.dostips.com/DtTipsStringManipulation.php#Snippets.Remove

-1
@ECHO OFF

SET string=
SET /A stringLength=0

:CheckNextLetter
REM Subtract the first letter and count up until the string="".
IF "%string%" NEQ "" (
    SET string=%string:~1%
    SET /A stringLength=%stringLength%+1
    GOTO :CheckNextLetter
) ELSE (
    GOTO :TheEnd
)

:TheEnd
    ECHO There is %stringLength% character^(s^) in the string.
PAUSE

This works for me. Hope this is useful for someone else. No need to adjust for any length. I just remove the first letter and compare against "" until the string equals "".

1
  • Your answer is virtually the same as the one from John with the same problems. It's slow and fails for strings containing special characters
    – jeb
    Commented Aug 10, 2021 at 7:16
-1

You can try this code. Fast, you can also include special characters

@echo off
set "str=[string]"
echo %str% > "%tmp%\STR"
for %%P in ("%TMP%\STR") do (set /a strlen=%%~zP-3)
echo String lenght: %strlen%
1
  • 1
    Same as the one of Joshua Honig fro 2011, but your solution also changes the working directory
    – jeb
    Commented Dec 28, 2019 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.