Re: Count the occurance of a charactor in a string (105 Views)
Reply
Regular Advisor
Smucker
Posts: 127
Registered: ‎12-18-1997
Message 1 of 4 (105 Views)
Accepted Solution

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
Please use plain text.
Honored Contributor
Biswajit Tripathy
Posts: 508
Registered: ‎12-11-2004
Message 2 of 4 (105 Views)

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
:-)
Please use plain text.
Honored Contributor
Peter Godron
Posts: 4,470
Registered: ‎02-13-2002
Message 3 of 4 (105 Views)

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
Please use plain text.
Regular Advisor
Smucker
Posts: 127
Registered: ‎12-18-1997
Message 4 of 4 (105 Views)

Re: Count the occurance of a charactor in a string

Thanks that did the trick
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation