23

我在用大多数语言很容易完成的问题上遇到问题,但我似乎无法批量解决。我想提取字符串的最后一个字符。在伪代码中..

if var1.substring(var1.length, -1) = "0"
  do something

在英语中...如果字符串中的最后一个字符是 0 那么...

4

2 回答 2

54
set var=%var:~-1%

SET /?从 docco 的提示中看到。


@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)
于 2013-03-27T15:23:39.590 回答
6

Batch 不使用 C 风格的逻辑,因此您确实必须对其中的大部分内容进行不同的思考。

也就是说, String -right 似乎是你想要的:http: //www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString

%str:~-1%

这会让你得到最后一个角色。

于 2013-03-27T15:23:47.833 回答