We help IT Professionals succeed at work.

How to count  a special character in a string with window batch?

jl66 asked
Have a string like  str=C:\a\b\c\dd\t.txt
Don't know how deep the directory is. How to count how many slashes?
I have no problem to count any char, but the \ is a bit different. Please any guru shed some light on it?
Watch Question



Thanks for the info. However I need a count of how many '\' there are in the str. How to get it?
Most Valuable Expert 2019
Most Valuable Expert 2018
This should do the trick:
@echo off
setlocal enabledelayedexpansion
set str=C:\a\b\c\dd\t.txt
call :GetCharCount BackslashCount "%str%" "\"
echo Backslashes found: %BackslashCount%

REM ***** Only functions below this line *****
goto :eof
:GetCharCount <Variable> <string> <Char>
set String=%~2
set /a i = 0
set /a CharCount = 0
set Char=!String:~%i%,1!
if not "%Char%"=="" (
	if /i "%Char%"=="%~3" (set /a CharCount += 1)
	set /a i+= 1
	goto GetCharCountLoop	
endlocal&set %~1=%CharCount%
goto :eof

Open in new window

Bill PrewTest your restores, not your backups...
Expert of the Year 2019
Top Expert 2016

No points for me on this one, but I sometimes use a FOR /L for this one oBdA to avoid GOTO.  I really don't like those because they have to read each line of the script from the top to find the label.  I tend to use EXIT /B rather than GOTO :EOF for that reason, although I have no sure way of knowing if GOTO is smart enough to handle :EOF special and fast.

I know we think of things a little differently from time to time, I enjoy that about reading your posts.  I decided to give up the SETLOCAL in the sub (even though I like that!) and instead directly access the result variable in the loop adding to it real time.  As a result I had to clear out the one variable needed by the sub on exit.  Anyway, just wanted to share a slightly different approach, but you already provided a viable approach, this was more for tinkering for me.

:GetCharCount <Variable> <string> <Char>
  set _S=%~2
  set /a %~1 = 0
  for /L %%i in (0,1,10000) do (
    if "!_S:~%%i,1!"=="" (set "_S=" & exit /b)
    if /i "!_S:~%%i,1!"=="%~3" set /a %~1 += 1
  set "_S="
  exit /b

Open in new window



Excellent! Thanks for bp's comment.