How to count only quotes/characters in a string
Posted: 05 Jun 2012 08:17
Sometimes it's useful to count a single character in a string, and not all characters like stringLength function do.
There is the obvious solution to iterate over the complete string and examine each character, but I don't like this brute force way.
So I decide to create an other more elegant solution.
The core idea is to replace rearrange the string so that each quote (or the character you want) will be replaced with the string +1,
and all other characters will be completly removed.
For this I use a technic, I called it delayed reduction, to do the magic work.
The sample string
The dog said : "Hello you", the cat answered: "Hi" and smile
will be replaced to
-1!!#:X=The dog said : !!#:X=Hello you!!#:X=, the cat answered: !!#:X=Hi!!#:X= and smile!
The content of the variable # is +1, so after the exclamation marks are expanded the line is reduced to
-1+1+1+1+1+1
And this can be easily calculated with SET/a to 4.
The rest of the code is only to avoid problems with special characters like exclamation marks and carets in the string.
jeb
There is the obvious solution to iterate over the complete string and examine each character, but I don't like this brute force way.
So I decide to create an other more elegant solution.
The core idea is to replace rearrange the string so that each quote (or the character you want) will be replaced with the string +1,
and all other characters will be completly removed.
For this I use a technic, I called it delayed reduction, to do the magic work.
The sample string
The dog said : "Hello you", the cat answered: "Hi" and smile
will be replaced to
-1!!#:X=The dog said : !!#:X=Hello you!!#:X=, the cat answered: !!#:X=Hi!!#:X= and smile!
The content of the variable # is +1, so after the exclamation marks are expanded the line is reduced to
-1+1+1+1+1+1
And this can be easily calculated with SET/a to 4.
The rest of the code is only to avoid problems with special characters like exclamation marks and carets in the string.
Code: Select all
:::::::::::::::::::::::::::::::::::::::::::
:CountQuotes <stringVar> <result>
setlocal EnableDelayedExpansion
set "line=!%~1!"
set "#=+1"
rem DelayedExpansion: double all quotes
set "line=!line:"=""!"
rem DelayedExpansion: remove all carets ^
set "line=!line:^=!"
rem PercentExpansion: Remove all !
set "line=%line:!=%"
rem PercentExpansion: Replace double quotes to !!#:#=
set "line=-1^!#:#=%line:""=^!^!#:#=%"
for /F "delims=" %%X in ("!line!") do (
set /a count=%%X!
)
(
endlocal
set %~2=%count%
exit /b
)
jeb