Link to home
Create AccountLog in
Avatar of jl66
jl66Flag for United States of America

asked on

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

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?
Avatar of jl66
Flag of United States of America image


Thanks for the info. However I need a count of how many '\' there are in the str. How to get it?
Avatar of oBdA

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Bill Prew
Bill Prew

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

Avatar of jl66


Excellent! Thanks for bp's comment.