0

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
0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
@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

4 Comments

I tried it but still did not worked...
There was a % missing from "%code:~-1%" - fixed now.
var names in .bat are not case sensitive? ( set Code ... %code ...) . No worrries, just currious. Thnks!
The only thing in the language itself that is case-sensitive is the alphabetic metavariables used to control for loops. When comparing data, like if "string1"... or find "something" then the data is case-sensitive and there is a switch to tell the command to ignore case (find /i "something" for instance)
1

Here's a quick example which gets help from PowerShell:

@Echo Off
SetLocal EnableExtensions
Set "Code=AAABASDG"
For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
 -NoProfile "[RegEx]::Matches('%Code%','A').Count"') Do Set "C=%%G"
Echo(%C%
Pause

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.