Copy Code code as follows:
@echo Off & setlocal enabledelayedexpansion
:: Calculating the length of a string
::
::
: Began
Set mystr=
set/p mystr= Enter a string to calculate the length (Direct return exit):
If not defined mystr goto:eof
FOR/L%%i in (0,1,1000) do if "!mystr:~%%i,1!" = = "" Set strlen=%%i && goto: _endfor
: _endfor
:: Echo String: "%mystr%"
Echo Length:%strlen%
Set strlen=
Goto began
The disadvantage of the scheme is that it cannot be detected when the string is longer than 1000, but the length that the variable can receive cannot be more than 1000.
Another option:
@echo off
:: Based on Willsort ' s codes code by JM 2006-10-9 CMD@XP
:: Source: http://www.cn-dos.net/forum/viewthread.php?tid=19819
Set mystr=
set/p mystr= Enter a string to calculate the length (Direct return exit):
If not defined mystr goto:eof
Set count=0
Setlocal enabledelayedexpansion
: Intercept
set/a count+=1
for/f%%i in ("%count%") does if not "!mystr:~%%i,1!" = = "" Goto Intercept
Echo Length:%count%
Pause
Goto:eof
@echo off
::
::
: Began
set/p mystr= Enter a string to calculate the length:
echo%mystr:~0,1% | findstr/i "q" 1>nul 2>nul && exit REM input Q exit
Call:bflen "%mystr%" REM, which calls Bflen, returns the length to the variable ret.
echo string: "%mystr%"
Echo Length:%ret%
Goto began
: Bflen rem really troublesome, initialization to be taken out alone.
Set num=
Set str=
Set ret=
Set str=%1
: Len REM Compute string length
Set str=%str:~0,-1%
set/a num =%num% + 1
If defined str goto len
SET/A ret =%num%-2
Set num=
Goto:eof