Avatar of jl66
jl66
Flag 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?
Windows BatchWindows 7

Avatar of undefined
Last Comment
jl66

8/22/2022 - Mon
jl66

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

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
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

~bp
jl66

ASKER
Excellent! Thanks for bp's comment.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck