Page 1 of 1

String count

Posted: 11 Nov 2008 15:54
by spam_killer
Hello..

How can I count alphabets in a string?
Let say I have string "many times during this day" so I want the output to be include the space = 26

I try to use FOR loop but It takes too long to finish as I have a long string in a text file.. Is there any solution ?

Posted: 22 Nov 2008 23:48
by DosItHelp
Hi spam_killer,

You could use a loop, however the :strLen function performs better as strings get bigger:
http://www.dostips.com/DtCodeCmdLib.php#Functions_strLen

Code: Select all

set "str=many times during this day"
call:strLen str len
echo.string length is: %len%
goto:eof

rem Copy function below here

DosItHelp? :wink:

How it work?

Posted: 17 Jan 2009 04:45
by spam_killer
Not working..

Posted: 17 Jan 2009 23:47
by DosItHelp
spam_killer

What error do you get?

Code: Select all

@Echo Off
Setlocal Enableextensions

set "str=many times during this day"
call:strLen str len
echo.string length is: %len%
goto:eof

rem Copy function below here

:strLen string len -- returns the length of a string via binary search, maximum length 1023
::                 -- string [in]  - variable name containing the string being measured for length
::                 -- len    [out] - variable to be used to return the string length
:$created 20081122 :$changed 20081122 :$categories StringOperations
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set "str=A!%~1!"&rem keep the A up front to ensures we get the length and not the upper bound
                 rem it also avoids trouble in case of empty string
set len=0
set /a "n=1<<10"&rem 2^10=1024
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
set /a "n>>=1, len|=n"
 if "!str:~%len%!"=="" set /a "len&=~n"
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" SET "%~2=%len%"
)
EXIT /b

Should output:
string length is: 26

What's the problem you see?