Operating System - HP-UX
1748128 Members
3806 Online
108758 Solutions
New Discussion юеВ

Re: Count the occurance of a charactor in a string

 
SOLVED
Go to solution
Smucker
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 3
Biswajit Tripathy
Honored Contributor

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
:-)
Peter Godron
Honored Contributor
Solution

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
Smucker
Regular Advisor

Re: Count the occurance of a charactor in a string

Thanks that did the trick