1.

Solve : return the nth character of a string?

Answer»

Hello again,
If I want the 5th character of a string, I can pretty easily get it like this
Code: [Select]C:\>SET a=santiago
C:\>ECHO %a:~5,1%
iBut does anyone knows how to get the nth character (where n is a variable)?
Code: [Select]C:\>SET a=santiago
C:\>SET n=5
C:\>ECHO %a:~%n%,1%
santiagon%,1%Thanks in advance
SantiagoCode: [Select][quote]
If I want the 5th character of a string, I can pretty easily get it like this

C:\>SET a=santiago
C:\>ECHO %a:~5,1%

Actually that code extracts the sixth character. The 5 represents OFFSET (zero-based) not position.

This snippet duplicates your code and retrieves the sixth character. The code is written for batch file use only.

Code: [Select]@echo off
set a=Santiago
set n=5
for /l %%i in (%n%,1,%n%) do (
call set bit=%%a:~%%i,1%%
)
echo %bit%

PS. Sometimes you have to read between the lines of previously posted answers. Although the question was different, the technique is remarkably close to your request.Thanks Sidewinder,
You're TOTALLY RIGHT about the fact that 5 is an offset and not a position.
and great job for the snippet. It WORKS fine.Quote from: Sidewinder on November 25, 2008, 06:34:06 AM

for /l %%i in (%n%,1,%n%) do (
call set bit=%%a:~%%i,1%%
)

it can be simpler:
Code: [Select]for %%i in (%n%) do call set bit=%%a:~%%i,1%%
THANK you Prince_


Discussion

No Comment Found