A frequent question at the SAS Online Community is this. How do I reverse the characters in a string or sentence in SAS? Today, I will provide a few approaches to this problem. I will keep things simple and primarily use the Reverse Function and the Revers Character Format.

Reverse All Characters in String in SAS

First let us see how to reverse all characters in a string in SAS. This means that the last character becomes the first. The penultimate character becomes the second character and so on. In the example below, I use the Reverse Function on the string “the quick brown fox jumps over the lazy dog”. The result is eht kciuq nworb xof spmuj revo eht yzal god. As expected.

data _null_;
   s = "the quick brown fox jumps over the lazy dog";
   r = reverse(s);
   put r=;
run;

Next, I do not actually change the string or save a new string. I simply use a character format to put the reversed string in the log. For more examples, see the Documentation for the Revers. Format.

data _null_;
   s = "the quick brown fox jumps over the lazy dog";
   put s $revers43.;
run;

In the example below, I use the Revers. Format again. However, I use the Put Function to create a new character variable. The result is similar to the one above.

data _null_;
   s = "the quick brown fox jumps over the lazy dog";
   r = put(s, $revers43.);
   put r=;
run;

Maintain Word Order, Reverse Characters in Words

As a final example, let us see how to reverse the characters in each word. However, we want to remain the order of the words themselves. Take a look at the code below. Here, I use a simple Do Loop and use the Countw Function to find out how many times to iterate. Within each iteration I use the Catx Function and the Reverse Function to create a new string. The result is the string “eht kciuq nworb xof spmuj revo eht yzal god”. We successfully reverse each word, but maintain the original word order.

data _null_;
   s = "the quick brown fox jumps over the lazy dog";
   length r $ 200;
   do i = 1 to countw(s);
      r = catx(" ", r, reverse(scan(s, i)));
   end;
   put r=;
run;

Summary

In this blog post, we see simple examples of how to reserve character strings in SAS. In the post, I use the well-known sentence “the quick brown fox jumps over the lazy dog”. Did you know that this is a Pangram?

You can download the entire code from this post here.