如何获取批处理文件中的字符串长度? [英] How do you get the string length in a batch file?

查看:49
本文介绍了如何获取批处理文件中的字符串长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有一种简单的方法可以在批处理文件中获取字符串的长度.例如,

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=???

如何求MY_STRING的字符串长度?

如果字符串长度函数处理字符串中所有可能的字符(包括转义字符),则加分项,例如:!%^^()^!.

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

推荐答案

由于没有内置的字符串长度函数,你可以像这样编写自己的函数:

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
)

这个函数总是需要 13 个循环,而不是一个需要 strlen-loops 的简单 strlen 函数.
它处理所有字符.

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

奇怪的表达式(set^ tmp=!%~2!)是处理超长字符串所必需的,否则无法复制.

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

这篇关于如何获取批处理文件中的字符串长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆