stallingOne
stallingOne

Reputation: 4006

How to replace specifically the nth word in a string in SAS

In sas, how can I replace specifically the i-th word in a string?

Let's say I have a string like this:

myString = 'aa cccc ddd aa aa 0.85645';

(=6 words) where I don't know the length of each word, I only know they are separated by spaces.

how can I replace the i-th string with something else like

e.g. if i=4 and I want replace the word with 'bbbbb':

myNewString = 'aa cccc ddd bbbbb aa 0.85645';

I'm looking for a function that would be some sort of a combination of scan(myString,4,' ') and tranwrd.

The problem here is that I can't combine them because the 1st word might be the same and the 4th word and thus I can't target specifically a tranwrd on the 4th word. I also can't use find() for the same reason.

Upvotes: 1

Views: 1441

Answers (2)

data _null_
data _null_

Reputation: 9109

Call SCAN make this easy.

38         data _null_;
39            String = 'aa cccc ddd aa aa 0.85645';
40            call scan(string,4,p,l,' ');
41            string2 = substrn(string,1,p-1)||'Dummy'||substrn(string,p+l);
42            put _all_;
43            run;

String=aa cccc ddd aa aa 0.85645 p=13 l=2 string2=aa cccc ddd Dummy aa 0.85645 _ERROR_=0 _N_=1

Upvotes: 4

user667489
user667489

Reputation: 9569

Here is one way of doing this. Regex might also be worth looking into.

data example;
myString = 'aa cccc ddd aa aa 0.85645';
length myWord  $32 t_myString $1000;
myWord = 'Dummy';
do i = 1 by 1 while (myWord ne '');
myWord = scan(myString,i,' ');
if i = 4 then myWord = 'bbbbb';
t_mystring = catx(' ',t_myString,myWord);
end;
myString = t_myString;
drop myWord t_myString;
run;

Upvotes: 1

Related Questions