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

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

问题描述

有没有出现是一个简单的方法来在批处理文件中的字符串的长度。如,

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 build in function for string length, you can write your own function.

@echo off
setlocal
set "myString=abcdef!%%^^()^!"
call :strlen result myString
echo %result%
goto :eof

:strlen <resultVar> <stringVar>
(   
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" ( 
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)
( 
    endlocal
    set "%~1=%len%"
    exit /b
)

此功能总是需要13环,而不是它需要的strlen-循环简单strlen函数。结果
它可以处理所有的字符。

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

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

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