I am trying to replace the nth word of a string and i am struggling to find an efficient way of doing it.
Below are a couple of ugly inefficient soloutions.
Code:
clear set obs 1 local mytext = "to be or not to be, that is the question" gen text = "`mytext'" local wordN = wordcount("`mytext'") gen newword= "" forvalues i = 1/`wordN' { if `i'==7 { replace newword= newword + " "+"it" } else { replace newword= newword + " "+ word(text, `i') } } list
Code:
clear set obs 1 local mytext = "to be or not to be, that is the question" gen text = "`mytext'" split text, gen(word) replace word7 = "it" egen newword = concat(word*), punct(" ") list
I was imagining there was a function called subword(text,re) or something more direct and more efficient.
Thanks
Adrian
0 Response to Replacing the nth word of a string
Post a Comment