Quartz | Level 8

## how to populate string in reverse order

How to populate the string in reverse order. For example I have a variable under name

 Fname Praveen Kumar Gowtham  Kuppal KK Hari Haran M

I want the output to be in the required format:

 Fname Kumar Praveen KK Kuppal Gowtham M Haran Hari

4 REPLIES 4
Tourmaline | Level 20

## Re: how to populate string in reverse order

One way

``````data have;
input Fname \$50.;
datalines;
Praveen Kumar
Gowtham Kuppal KK
Hari Haran M
;

data want;
set have;
length FnameNew \$ 50;
do _N_ = countw(Fname) to 1 by -1;
FnameNew = catx(' ', FnameNew, scan(Fname, _N_));
end;
run;``````

Result:

```Fname              FnameNew
Praveen Kumar      Kumar Praveen
Gowtham Kuppal KK  KK Kuppal Gowtham
Hari Haran M       M Haran Hari ```

## Re: how to populate string in reverse order

What should happen if the name consists of four words?

PROC Star

## Re: how to populate string in reverse order

I would recommend @PeterClemmensen's solution over the code in this post as it works with any number of names  (see question from @andreas_lds).

When I saw "reverse" in the title I just thought how might the reverse() function be used, so just for demonstration purposes, the following produces the required result for the input data provided:

``````data want;
set have;

length name2 \$ 50;

name2 = reverse(catx(' '
,reverse(scan(fname,1))
,reverse(scan(fname,2))
,reverse(scan(fname,3))
));
run;
``````

Kind regards,

Amir.

Barite | Level 11

## Re: how to populate string in reverse order

You can place the fname word parts, reversely indexed in a loop, in an array (i.e. conceptually a 'reverse/split') and perform a single CATX after the loop.

Example:

```data have;
input Fname \$50.;
datalines;
Praveen Kumar
Gowtham Kuppal KK
Hari Haran M
;

data want;
set have;

array items(0:49) \$50 _temporary_;

do _n_ = 1 to countw(fname);
items(dim(items)-_n_) = scan(fname, _n_);
end;

fname = catx(' ', of items(*));
run;```
Discussion stats
• 4 replies
• 800 views
• 4 likes
• 5 in conversation