我遇到的问题很容易在大多数语言中完成,但我似乎无法批量解决。我想提取字符串的最后一个字符。在伪代码..
if var1.substring(var1.length, -1) = "0"
do something
英文...如果字符串中的最后一个字符是0,那么......
答案 0 :(得分:42)
set var=%var:~-1%
从docco的提示中查看SET /?
。
@ECHO OFF
SETLOCAL
SET var=abcd
SET var2=%var:~-1%
CALL :show "-1"
SET var2=%var:~-2%
CALL :show "-2"
SET var2=%var:~-3%
CALL :show "-3"
SET var2=%var:~1%
CALL :show "1"
SET var2=%var:~2%
CALL :show "2"
SET var2=%var:~3%
CALL :show "3"
SET var2=%var:~0,1%
CALL :show "0,1"
SET var2=%var:~0,2%
CALL :show "0,2"
SET var2=%var:~0,3%
CALL :show "0,3"
SET var2=%var:~0,-1%
CALL :show "0,-1"
SET var2=%var:~0,-2%
CALL :show "0,-2"
SET var2=%var:~0,-3%
CALL :show "0,-3"
SET var2=%var:~1,-1%
CALL :show "1,-1"
SET var2=%var:~1,-2%
CALL :show "1,-2"
SET var2=%var:~1,-3%
CALL :show "1,-3"
GOTO :eof
:show
echo Test with "var:~%~1" : var=%var% var2=%var2%
GOTO :eof
结果:
Test with "var:~-1" : var=abcd var2=d
Test with "var:~-2" : var=abcd var2=cd
Test with "var:~-3" : var=abcd var2=bcd
Test with "var:~1" : var=abcd var2=bcd
Test with "var:~2" : var=abcd var2=cd
Test with "var:~3" : var=abcd var2=d
Test with "var:~0,1" : var=abcd var2=a
Test with "var:~0,2" : var=abcd var2=ab
Test with "var:~0,3" : var=abcd var2=abc
Test with "var:~0,-1" : var=abcd var2=abc
Test with "var:~0,-2" : var=abcd var2=ab
Test with "var:~0,-3" : var=abcd var2=a
Test with "var:~1,-1" : var=abcd var2=bc
Test with "var:~1,-2" : var=abcd var2=b
Test with "var:~1,-3" : var=abcd var2=
对于IF
声明,请尝试
IF "%var:~-1%"=="0" (dosomething) else (dosomethingelse)
答案 1 :(得分:5)
批处理不使用C样式逻辑,所以你必须对它的大部分内容进行不同的思考。
那就是说,String -right似乎是你想要的: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
%str:~-1%
那会让你成为最后一个角色。