BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
dber
Calcite | Level 5

How do remove the last 5 characters from a char string regardless of length?

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20
data _null_;
   string="abcdefghijklx";
   newstring=substr(string, 1, length(string)-5);
   put newstring;
run;

View solution in original post

7 REPLIES 7
Reeza
Super User

SUBSTR() + REVERSE()

SUBSTR() + LENGTH()

 


@dber wrote:

How do remove the last 5 characters from a char string regardless of length?

Thanks


 

PeterClemmensen
Tourmaline | Level 20
data _null_;
   string="abcdefghijklx";
   newstring=substr(string, 1, length(string)-5);
   put newstring;
run;
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Just a note that you may want lengthn() to avoid extra spaces at the end.

PeterClemmensen
Tourmaline | Level 20

Right you are 🙂

ballardw
Super User

@PeterClemmensen wrote:
data _null_;
   string="abcdefghijklx";
   newstring=substr(string, 1, length(string)-5);
   put newstring;
run;

You may want to check that the length of the string is actual greater than or at least 5 to prevent error messages.

Just in case there are shorter than expected string values.

   if length(string) ge 5 then newstring=substr(string, 1, length(string)-5);
gamotte
Rhodochrosite | Level 12

or use substrn :

 

data _null_;
   string="abcd";
   newstring=substrn(string, 1, length(string)-5);
   put newstring=;
run;
novinosrin
Tourmaline | Level 20

If the objective is just to remove and not create a new variable, you can use just this

 

data want;
   string="abcdefghijklx";
  substr(string, length(string)-5)=' ';
run;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 7 replies
  • 40162 views
  • 8 likes
  • 7 in conversation