DATA Step, Macro, Functions and more

replace every nth word with a nth word concatenated with a symbol

Accepted Solution Solved
Reply
Trusted Advisor
Posts: 1,131
Accepted Solution

replace every nth word with a nth word concatenated with a symbol

Dear Expert,

 

Could you please help me concatenate every nth word with a symbol.

 

Consider that i have a string data like below

 

"having a common variable to merge by ensures that the"

 

the expected output should be

 

"having a common * variable to merge * by ensures that * the"

 

So after every 3rd word i have to place the symbol(*). like above.

 

Could you please suggest a solution.

 

Thanks,

Jag

Thanks,
Jag

Accepted Solutions
Solution
‎10-22-2015 02:28 PM
Respected Advisor
Posts: 4,663

Re: replace every nth word with a nth word concatenated with a symbol

Put the CATx functions to good use:

 

data test;
length subStr outStr $200;
inStr = "having a common variable to merge by ensures that the";
do i = 1 by 3 until(Missing(subStr));
    subStr = catx(" ", scan(inStr,i), scan(inStr,i+1), scan(inStr,i+2));
    outStr = catx(" * ", outStr, subStr);
    end;
drop subStr i;
run;

proc print data=test noobs; run;
PG

View solution in original post


All Replies
Solution
‎10-22-2015 02:28 PM
Respected Advisor
Posts: 4,663

Re: replace every nth word with a nth word concatenated with a symbol

Put the CATx functions to good use:

 

data test;
length subStr outStr $200;
inStr = "having a common variable to merge by ensures that the";
do i = 1 by 3 until(Missing(subStr));
    subStr = catx(" ", scan(inStr,i), scan(inStr,i+1), scan(inStr,i+2));
    outStr = catx(" * ", outStr, subStr);
    end;
drop subStr i;
run;

proc print data=test noobs; run;
PG
Trusted Advisor
Posts: 1,131

Re: replace every nth word with a nth word concatenated with a symbol

Thank you so much PG , it worked
Thanks,
Jag
Respected Advisor
Posts: 3,124

Re: replace every nth word with a nth word concatenated with a symbol

[ Edited ]

Here is another way:

 

data test;
length outStr $200;
inStr = "having a common variable to merge by ensures that the";
outstr=prxchange('s/((\w+ ){3})/$1* /', -1, instr);
run;

This is to tell SAS adding * right after the 3rd word, in a literal sense. 

Trusted Advisor
Posts: 1,131

Re: replace every nth word with a nth word concatenated with a symbol

Thank you Haikuo it was wonderful.
Thanks,
Jag
🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 279 views
  • 3 likes
  • 3 in conversation