String count

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
spam_killer
Posts: 12
Joined: 10 Oct 2008 04:50

String count

#1 Post by spam_killer » 11 Nov 2008 15:54

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 ?

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#2 Post by DosItHelp » 22 Nov 2008 23:48

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:

spam_killer
Posts: 12
Joined: 10 Oct 2008 04:50

How it work?

#3 Post by spam_killer » 17 Jan 2009 04:45

Not working..

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#4 Post by DosItHelp » 17 Jan 2009 23:47

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?

Post Reply