計算字串的長度的多種解決方案集錦

來源:互聯網
上載者:User

複製代碼 代碼如下:@echo off & setlocal EnableDelayedExpansion
:: 計算字串的長度
::
::
:began
set mystr=
set /p mystr=輸入要計算長度的字串(直接斷行符號退出):
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 字串: "%mystr%"
echo 長 度: %strlen%
set strlen=
goto began

該方案的缺陷是:當字串長度超過1000的時候,將不能探測到;不過變數能接收的長度好象還不能超過1000

另外一種方案:

複製代碼 代碼如下:@echo off
:: Based on willsort's codes code by JM 2006-10-9 CMD@XP
:: 出處:http://www.cn-dos.net/forum/viewthread.php?tid=19819
set mystr=
set /p mystr=輸入要計算長度的字串(直接斷行符號退出):
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 長 度: %count%
pause
goto :eof

@echo off
::
::
:began
set /p mystr=輸入要計算長度的字串:
echo %mystr:~0,1% | findstr /i "q" 1>nul 2>nul && exit rem 輸入q退出

call :bflen "%mystr%" rem 這兩句調用bflen,返回長度到變數ret中。
echo 字串: "%mystr%"
echo 長 度: %ret%

goto began

:bflen rem 真麻煩,初始化要單獨拿出來。
set num=
set str=
set ret=
set str=%1
:len rem 計算字串長度
set str=%str:~0,-1%
set /a num = %num% + 1
if defined str goto len
set /a ret = %num% - 2
set num=
goto :eof

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.