Home > database >  Batch for loop find string in variable
Batch for loop find string in variable

Time:01-15

I want to find the string A in the variable Code=AAABASDG and count each time 1 up if "A" was found so the result should be that it outputs 4 because in Code variable there are 4 A's

Example Code :

@echo off
set /A C=0
set Code=AAABASDG
for %%i in (%Code%) do IF "%%i"=="A" set /A C=%C% 1
echo %C%
pause

CodePudding user response:

You could get the length of original string A, then delete the "A" letters from the string and get the length of the result, to finally subtract both lengths.

To easily get the length of the string, you could store it in a file and then ask for the %%~Z size of the file. Here it is:

@echo off
setlocal 

set "Code=AAABASDG"
> before.txt echo %code%
> after.txt echo %code:A=%
for %%b in (before.txt) do for %%a in (after.txt) do set /A "count=%%~Zb-%%~Za"
echo %count%

The only drawback of this method is that it is not case-aware: both upcase and lowcase letters are delete in the replacement operation

CodePudding user response:

@echo off
set /A C=0
set "Code=AAABASDG"
:loop
if defined code (
 if "%code:~-1%"=="A" set /a C =1
 set "code=%code:~0,-1%"
 goto loop
)
echo %C%

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier.

Substrings in batch are obtained from %var:~m,n% where ,n is optional; m is count-of-chars-from-beginning-of-string, from end if negative. ,n positive = max length to return; negative = end-position in chars from end; missing=return all after m

  • Related