Help using Base SAS procedures

Remove Duplicate Characters In A String

Reply
Super Contributor
Posts: 358

Remove Duplicate Characters In A String

Hi All:

I'm having a huge brain cramp today.

I want to remove any repeated characters in a character string. I've gone through all the character functions in the doc and I can't find anything to do what I want.

For example:

change: YYYMMDD
to: YMD

Sounds simple, but I just can't seem to wrap my head around this one.

Thanks in advance.
Super Contributor
Super Contributor
Posts: 3,174

Re: Remove Duplicate Characters In A String

This macro should work for you:

%macro strnodup(strvar);
drop __i;
__i=1;
do until(__i = length(&strvar));
if substr(&strvar,__i,1) = substr(&strvar,__i+1,1) then
&strvar = substr(&strvar,1,__i)!!substr(&strvar,__i+2);
else __i + 1;
end;
%mend strnodup;

data _null_;
retain str "YYYMMDD";
str_old = str;
%strnodup(str);
putlog _all_;
run;


Scott Barry
SBBWorks, Inc.
N/A
Posts: 0

Re: Remove Duplicate Characters In A String

Repeated characters:
change: "YMYDD"
to: ?
Respected Advisor
Posts: 3,887

Re: Remove Duplicate Characters In A String

HTH
Patrick

data _null_;
RId = prxparse('s/(.)\1+/$1/io');
text = 'YYYMMDD__YDDDM';
call prxchange(RId, -1, text);
put text;
run;
Valued Guide
Posts: 2,174

Re: Remove Duplicate Characters In A String

just another way ..... using substr() in 2 ways (as source and as destination)[pre] data ;
set whatever ;
do p= 2 to length( string) while( p le length( string ) ) ;
if substr( string, p, 1) = substr( string, p-1, 1)
then substr( string, p ) = substr( string, p+1 ) ;
end ;
drop p ;
run ;[/pre]
PeterC

sorry, on testing, I found this failed to handle triples. So here are some test data and a working approach[pre]data whatever ;
input string $ ;
cards ;
qweeertyui
opassassaa
dfgggfggh
jklsxcvb
nm,.1234
5678tttt
ttfghj56
data ;
set whatever ;
do p= 2 to length( string) while( p le length( string ) ) ;
if substr( string, p, 1) = substr( string, p-1, 1) then
do ;
substr( string, p ) = substr( string, p+1 ) ;
p = p-1 ;
end ;
end ;
drop p ;
run ;[/pre] 17:04 11Oct08 BST


Message was edited by: Peter.C
Ask a Question
Discussion stats
  • 4 replies
  • 1682 views
  • 1 like
  • 5 in conversation