Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last character of a string from a variable

I am having issues with a problem accomplished very easily in most languages but I can't seem to figure it out in batch. I want to extract the last character of a string. In pseudo code..

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

In english...if the last character in the string is 0 then...

like image 927
mgrenier Avatar asked Mar 27 '13 15:03

mgrenier


People also ask

How do I get the last 5 characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string.

How do you get the last character of a string in Python?

Just use a negative number starting at -1 to select a character in the string. In the case of the index at -1 Python will select the last index of the string.


2 Answers

set var=%var:~-1%

see SET /? from the prompt for 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

Results:

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=

For your IF statement, try

IF "%var:~-1%"=="0" (dosomething) else (dosomethingelse)
like image 187
Magoo Avatar answered Oct 23 '22 05:10

Magoo


Batch does not use C style logic, so you really have to think differently for much of it.

That said, String -right appears to be what you want: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString

%str:~-1%

That will get you the last character.

like image 6
Austin T French Avatar answered Oct 23 '22 03:10

Austin T French