SAS Programming

DATA Step, Macro, Functions and more
BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
buechler66
Barite | Level 11

Hi folks.  I'm looking for a method to create a variable of the string up until the last blank space in the string.

 

nm1 =  'SAN ANTONIO CA';

nm2 =  'NEW SAN ANTONIO CA'

 

So for nm1 I'd want to return only 'SAN ANTONIO'

So for nm2 I'd want to return only 'NEW SAN ANTONIO'

 

Any thoughts on how to do this?  Basically the requirement is to return everything prior to the final blank space in the string? But the under of blank spaces may vary.

 

Any help would be appreciated.

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

Hi @buechler66  Please see if this helps

 

data have;
length nm $50;
nm =  'SAN ANTONIO CA';
output;
nm =  'NEW SAN ANTONIO CA';
output;
run;

data want;
 set have;
 length want $30;
 want=substr(nm,1,findc(trim(nm),' ','b')-1);
run;

Or something fancy

 

 want=prxchange('s/(.*)\s.+$/$1/',-1, trim(nm));

 

View solution in original post

4 REPLIES 4
novinosrin
Tourmaline | Level 20

Hi @buechler66  Please see if this helps

 

data have;
length nm $50;
nm =  'SAN ANTONIO CA';
output;
nm =  'NEW SAN ANTONIO CA';
output;
run;

data want;
 set have;
 length want $30;
 want=substr(nm,1,findc(trim(nm),' ','b')-1);
run;

Or something fancy

 

 want=prxchange('s/(.*)\s.+$/$1/',-1, trim(nm));

 

buechler66
Barite | Level 11

I appreciate you taking the time to help.  Greatly!

Tom
Super User Tom
Super User

It is easy to find the value after the last space

scan(name,-1,' ')

Once you have that you can figure out how many characters to chop off.

susbtrn(name,1,length(name)-length(scan(name,-1,' '))

But what do want to do when there are no embedded spaces?

name='LONDON';

Do you want an empty string?  Or do you want to remove nothing?

buechler66
Barite | Level 11
Ty for posting this. I appreciate ur time.

sas-innovate-white.png

Our biggest data and AI event of the year.

Don’t miss the livestream kicking off May 7. It’s free. It’s easy. And it’s the best seat in the house.

Join us virtually with our complimentary SAS Innovate Digital Pass. Watch live or on-demand in multiple languages, with translations available to help you get the most out of every session.

 

Register now!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 2559 views
  • 1 like
  • 3 in conversation