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

How can I remove the last word in a string?

1 ACCEPTED SOLUTION

Accepted Solutions
paulkaefer
Lapis Lazuli | Level 10

Good question. This was answered on StackOverflow as well as in this code example.

 

Essentially, you can pass -1 in to CALL SCAN to get the last word, and once you've found it, it's trivial to remove.

View solution in original post

5 REPLIES 5
paulkaefer
Lapis Lazuli | Level 10

Good question. This was answered on StackOverflow as well as in this code example.

 

Essentially, you can pass -1 in to CALL SCAN to get the last word, and once you've found it, it's trivial to remove.

tropical_surfer
Fluorite | Level 6

Thanks! Any advice on how to remove the second word from a string? I'm trying to check between two variables that excluding the 2nd word both strings are identical.

paulkaefer
Lapis Lazuli | Level 10

Try the same steps, but using CALL SCAN with a count of 2.

tropical_surfer
Fluorite | Level 6

That only keeps the first and 2nd word, but I want the entire string minus the 2nd word.

paulkaefer
Lapis Lazuli | Level 10

Oh, I see. Well in the StackOverflow post,

substr(starting_word,1,pos-2);

is used to return a string that includes all but the last word.

 

You'll probably need this:

call scan(original_string, 2, pos, length);

to get the length and position of the second word, then

first_piece = substr(original_string, 1, pos-1)

(maybe pos-2 to remove the space between the words)

 

and

second_piece = substr(original_string, pos+length, lengthOfString)

(you'll have to calculate lengthOfString using the LENGTH function)

 

Then use a CAT function (see here for a good description of the different choices) to combine first_piece and second_piece.

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
  • 5 replies
  • 13068 views
  • 1 like
  • 2 in conversation