Hi all,
I have a sentence like "I am a student in a college in a city in India to study masters"
in the above sentence, I want to replace the second occurrence of "in" with "from".
Can anyone suggest me code to replace it.
i have tried with the following code, i made it. But am looking for another way which makes easy to execute.
data x;
word = "I am a student in a college in a city in India to study masters";
substr(word, 29, 2) = "from";
run;
Thank you & regards.
Manoj
Like this?
NEWWORD=prxchange('s/(.*? in .*?)( in )(.*)/$1 from $3/',-1,WORD);
I hope there's no error, I can't test atm.
You probably want to use the TRANWRD function:
Word=tranwrd(Word,'to','from');
Thank you for replay,
by using TRANWRD all in 's will be replaced by "from", but i want to replace only second "in" with "from"
And what is the logic to assume that? Simply put, if you had the string:
I am a student in a college in a city in India to study masters
How are we to note that the second in is to be replaced, and not the others?
I mean I could tell you to substr or scan the string, but that would only help in this one specific case.
Like this?
NEWWORD=prxchange('s/(.*? in .*?)( in )(.*)/$1 from $3/',-1,WORD);
I hope there's no error, I can't test atm.
DATA TEMP;
word = "I am a student in a college in a city in INDIA to study masters";
word_len= LENGTH(STRIP(word));
fst_pos= FINDW(STRIP(word),'in');
snd_pos= FINDW(STRIP(word),'in',fst_pos+1);
new_str_part1= substr(STRIP(word),1,snd_pos-1);
new_str_part2= 'from';
new_str_part3= substr(STRIP(word),snd_pos+2);
new_word= CAT(new_str_part1,new_str_part2,new_str_part3);
DROP word_len fst_pos snd_pos new_str_part:;
run;
PROC PRINT DATA=TEMP;
RUN;
data x;
word = "I am a student in a college in a city in India to study masters ";
put word= ;
pid=prxparse('/\bin\b/i');
s=1;e=length(word);
call prxnext(pid,s,e,word,p,l);
n=0;
do while(p>0);
n+1;
if n=2 then do;want=substr(word,1,p-1)||'from'||substr(word,p+l);leave;end;
call prxnext(pid,s,e,word,p,l);
end;
put want= ;
run;
You already have your answer, both answers from @ChrisNZ and @Ksharp should work. I am here just to comment that your original example code will not work for your purpose. The reason being SAS using FIXED length variable, you will need byte abundancy or some walk-around (rename etc.) to replace with a longer chars, notice @Ksharp's example with some blanks padded.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.