Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Count the occurance of a charactor in a string

SOLVED
Go to Solution
Regular Advisor

Count the occurance of a charactor in a string

I need a code snippet to determine the number of numeric digits within a string.

Ex
str="jdydh7hdyd5"

cnt=`some_function $str`

echo $cnt

any ideas
3 REPLIES
Honored Contributor [Founder]

Re: Count the occurance of a charactor in a string

some_function ()
{
integer cnt=0
str1=$1
str2=`echo $str1 | sed 's/[0-9]//g'`
cnt=${#str1}-${#str2}
echo $cnt
}

str="jdydh7hdyd5"
some_function $str


Should print 2 as there are only 2 numeric digits in
the string str.

- Biswajit
:-)
Honored Contributor [Founder]

Re: Count the occurance of a charactor in a string

Smucker,
how about:

cnt=`echo $str | tr -cd "[0-9]" |wc -c`

this deletes all characters beside 0-9 and then counts the characters left

Shortest answer I could find at the moment.
Hope this solves your problem.

Regards
Highlighted
Regular Advisor

Re: Count the occurance of a charactor in a string

Thanks that did the trick