Get the App
SLTechnology News&Howtos  ›  Development  › 

How to calculate the length of a string using batch processing

Shulou Source: shulou.com Published: 2022-06-03 07:48:50 11月15日 Update

This article is about how to use batch processing to calculate the length of strings. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

The code is as follows:

@echo off & setlocal EnableDelayedExpansion

:: Calculate the length of a string

::

::

:began

set mystr=

set /p mystr= Enter the string to calculate the length (enter directly to 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 flaw of this scheme is that it will not be detected when the string length exceeds 1000; however, it seems that the length that the variable can accept cannot exceed 1000.

Another option:

@echo off

:: Based on willsort's codes code by JM 2006-10-9 CMD@XP

:: Source: www.cn-dos.net/forum/viewthread.php? tid=19819

set mystr=

set /p mystr= Enter the string to calculate the length (enter directly to exit):

if not defined mystr goto :eof

set count=0

setlocal enabledelayedexpansion

:intercept

set /a count+=1

for /f %%i in ("%count%") do if not "! mystr:~%%i,1! "=="" goto intercept

echo Length: %count%

pause

goto :eof

@echo off

::

::

:began

set /p mystr= Enter string to calculate length:

echo %mystr:~0,1% |findstr /i "q" 1>nul 2>nul && exit rem Enter q to exit

call :bflen "%mystr%" rem These two sentences call bflen and return the length to the variable ret.

echo string: "%mystr%"

echo Length: %ret%

goto began

:bflen rem is really troublesome, initialization has to be taken out separately.

set num=

set str=

set ret=

set str=%1

:len rem Calculates 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

Thank you for reading! About "how to use batch processing to calculate the length of strings" this article is shared here, I hope the above content can be of some help to everyone, so that everyone can learn more knowledge, if you think the article is good, you can share it to let more people see it!

Tags: Character string length input content variable scheme more article good practical code provenance tone article time see knowledge defect trouble Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Huawei Docker MariaDB Apple