Multiple solutions for calculating the length of strings _dos/bat

Source: Internet
Author: User
Tags goto strlen
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:

Copy Code code as follows:

@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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.