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

jl66
jl66 used Ask the Experts™
on
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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
jl66Consultant

Author

Commented:
Thanks for the info. However I need a count of how many '\' there are in the str. How to get it?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
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>
setlocal
set String=%~2
set /a i = 0
set /a CharCount = 0
:GetCharCountLoop
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...
Top Expert 2016

Commented:
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

~bp
jl66Consultant

Author

Commented:
Excellent! Thanks for bp's comment.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial