You might try the following script, providing the input string as (quoted) command line argument:
set "STRING=%~1$"
set STRING="%STRING:\=" "%"
set /A "COUNT=-1"
for %%E in (%STRING%) do set /A "COUNT+=1"
echo Count of `\`: %COUNT%
This replaces every character to be counted by "
+ SPACE + "
and encloses the entire string in between ""
, so the input string aa\bb\cc\dd\
becomes "aa" "bb" "cc" "dd" ""
. The resulting string is fed into a for
loop that recognises individual items to iterate through -- five in this case. The counter variable COUNT
is initialised with a value of -1
, so the result is not the number of iterated items but the separators, namely the \
characters present in the original string.
This approach fails if the string contains ?
or *
characters. It would also fail in case the character to count is one of the following: "
, %
, =
, *
, ~
.