DATA Step, Macro, Functions and more

Replacing all punctuation in a string with spaces

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 19
Accepted Solution

Replacing all punctuation in a string with spaces

Hi,

 

Is there a work around that I can use just one tranwrd function to replace all the special charaters in the string. I'm using below code to replace word by word using multiple variable.

 

data demo;
string='run along&the$wall#mister miller';
newstring1=tranwrd(string,'#',' ');
newstring2=tranwrd(newstring1,'&',' ');
newstring3=tranwrd(newstring2,'$',' ');
run;

Thanks.


Accepted Solutions
Solution
‎07-31-2017 12:47 PM
Super User
Posts: 19,876

Re: Replacing all punctuation in a string with spaces

Try TRANSLATE instead. 

View solution in original post


All Replies
Solution
‎07-31-2017 12:47 PM
Super User
Posts: 19,876

Re: Replacing all punctuation in a string with spaces

Try TRANSLATE instead. 

Super User
Super User
Posts: 7,079

Re: Replacing all punctuation in a string with spaces

Combine the translate function with the compress function. Use the modifiers for the compress function to tell it which characters you DON'T want to turn into spaces.

 

data test;
  string='run along&the$wall#mister miller';
  new_string=translate(string,' ',compress(string,,'ad'));
  put string $char100. / new_string $char100. ;
run;
run along&the$wall#mister miller
run along the wall mister miller
PROC Star
Posts: 326

Re: Replacing all punctuation in a string with spaces

you can use prxchange too

data demo;
string='run along&the$wall#mister miller';
string1= prxchange('s/&|\$|#/ /', -1, string);
run;
☑ This topic is solved.

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

Discussion stats
  • 3 replies
  • 138 views
  • 2 likes
  • 4 in conversation