Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: RE: strpos: cleaning string variables

From   Nick Cox <>
To   "''" <>
Subject   st: RE: strpos: cleaning string variables
Date   Mon, 21 Feb 2011 20:36:11 +0000

-strpos()- is a function, not a command. 

You can eliminate substrings of length 1 if you wish using -subinstr()-. As -subinstr()- can delete more than one occurrence at a time it is likely to be an answer to your question about the n th occurrence. 

Your loop is going to fail second time around if only because you are then trying to -generate- variables that already exist. Again, you don't need to loop over , . & as you can work on them using separate commands within the loop. 


Emily Farchy

I would like to run a loop to transform some messy names into cleaner versions eg
"Drs. H. Muslim Kasim, Ak"--> "Muslim Kasim"
"Drs. Makmur Syahputra, Sh" -->"Makmur Syah Putra"
"H Amru Helmy Daulay Sh" --> "Amru Helmy Daulay"

I was thinking of using the strpos command which seems like it might be useful but is there a way to get it to find the nth occurrence (eg of a space) and a way to eliminate substrings of for example 3 letters or less?

I was working on the following but get stuck when I pass the first occurence

foreach x of local xlist {
	**** get rid of . , or & in name (A, B --> A B; st. A -->  st A, A & B --> A and B)
	foreach z in , . & {
		qui gen `x'_bh= trim(substr(`x', 1, strpos(`x', "`z'")-1))
		qui gen `x'_ah= trim(substr(`x', strpos (`x', "`z'")+1, 50))
		qui gen `x'_mid= substr(`x', strpos (`x', "`z'"), 1)

		replace `x'=trim(`x'_bh+" "+`x'_ah)
		replace `x'=trim(`x'_bh+" and "+`x'_ah) if `x'_mid=="&"

		drop `x'_bh `x'_ah `x'_mid

*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index