Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Parse question


From   n j cox <[email protected]>
To   [email protected]
Subject   Re: st: Parse question
Date   Thu, 22 Sep 2005 16:12:18 +0100

I was wondering this the other day but didn't
remember anything. You could try -tokenize-
using the character in question, but then
you have to keep track of occurrences at
the beginning and end as well as in the middle.

Given this,

*! NJC 1.0.0 22 Sept 2005
program charcount, sclass
version 8
args string char garbage
if `"`char'"' == "" | `"`garbage'"' != "" error 198

local c = 0
forval i = 1/`= length(`"`string'"')' {
if substr(`"`string'"',`i',1) == `"`char'"' local ++c
}

sreturn local count = `c'
end

you should fire at it a quoted string and a quoted character,
e.g.

charcount "`loc'" "a"

and it will leave behind -s(count)- with the answer.

di s(count)

There's also no doubt a Mata solution.

Nick
[email protected]

[email protected]

Is there any way to count the number of occurence of a particular character in a local or global macro?
For example:
local loc (a mama baba).
I would like to count the number of occurences of "a" , in this case 5.
Or local loc "There; That; This)
I want to count the number of occurences of ";".
I am writing an ado for a work and I can't figure how to do it.
I have a look at macrolists but there is no mention of that case.


*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/




© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index