Aacini wrote: ↑28 Mar 2012 12:01
This is another, simpler method:
Code: Select all
@echo off
set mystring=example
:loop
if defined mystring (
echo(%mystring:~0,1%
set "mystring=%mystring:~1%"
goto loop
)
Hi,
I may be late for even the afterparty, but maybe it's worth reviving.
I tried to adapt Aacini's most elegant technique to browse through a text string character by character, as it seemed apt to remove "=" signs from a URL (text string) like this one:
https://www.some-site.com/index.php?p=a&select=59=1=&2=3&&=4?=55321=abcd
For such removal substring replacement cannot be used, because the equal sign is also the operator for such replacements.
(in the above URL I'll first replace the ampersands "&" by "¿", i.e. some character which I'll never run into in normal situations, and
which does not hinder my batch either, as it is accepted as ANSI. But this is not the issue here.)
But, when next I try Aacini's approach like this
Code: Select all
@echo off
setlocal EnableDelayedExpansion
set "name1=https://www.some-site.com/index.php?p=a¿select=59=1=¿2=3¿¿=4?=55321=abcd"
:loop
IF DEFINED name1 (
IF "%name1:~0,1%" EQU "=" (
set str=!str!¡
) ELSE (
set str=!str!%name1:~0,1%
)
set "name1=%name1:~1%"
GOTO loop
)
echo Modified string: !str!
pause
the batch crashes after the last time the IF DEFINED part is executed, with the error message "( was not expected at this time" flashing by. (in fact it's waaaay too quick to read, but with a camera one can do miracles.
)
This error message seems to hint that sth. goes wrong with the ending of the loop, and that it still tries to enter the code block after the string has been reduced to empty, instead of continuing with the "pause" command. But if that's the case, I can't explain it.
I'll add to this, that I'm not sure why this technique works with "mystring" (in the original code), i.e. without percent symbols around the variable, as I'd rather expect
%mystring
%.
Interestingly, the latter (i.e.
%name1
%) seems to work as well for my code, until it runs into another kind of problem (but no crash this time). The output string "str" is correct, until it reaches the
last "=" sign; next, the remainder of the string is no longer appended to "str". As if sth. else happens because of the "=" sign. But I have no clue...
NB:
expected output (variable "str") would be:
https://www.some-site.com/index.php?p¡a¿select¡59¡1¡¿2¡3¿¿¡4?¡55321¡abcd
Note that this may not be displayed correctly in your output screen (depending on system settings), but the preview of this forum's interface indicates that here they're displayed correctly.
Any suggestions to what goes wrong in the above code, are welcome, of course.
BatchGuy
(Win7 Ultimate, x64)