## Working with character variables

Solved
Frequent Contributor
Posts: 93

# Working with character variables

Hello

I have a string variable which contains letters and ';' signs. for example:  A;B;A;A;B;C

The length of these strings is not constant and varies by observations, so the next observation may be something like A;B or even a single B

I need to create variables to store each letter separately. for example for the first string, I need 6 separate variables, say alpha1, alpha2, alpha3, alpha4, alpha5 and alpha6 which each of them only contains one of the 6 letters appeared in the string. so alpha1 will be A, alpha2 will be B, alpha3 will be A and so on

For the second string, I will only need alpha1 to store A and alpha2 to storeB and finally for the third string, I just need alpha1 to store B and all other alpha variables to be empty.

My data base contains about 1 million observations so having a lot of if,then statements may not be the smartest solution.

Any suggestion is greatly appreciated!

Accepted Solutions
Solution
‎11-05-2012 09:25 PM
Posts: 3,167

## Re: Working with character variables

Something like this?

data have;

input var \$char20.;

CARDS4;

A;B;C;D;A;B

A;B;C

B;A;D;D

B

J;K;C;K;J;K;A;B;C;D

;;;;

proc sql;

select (max(length(var))+1)/2 into :vn from have;quit;

data want;

array alpha(&vn) \$1.;

set have;

do i=1 to dim(alpha) until (missing (alpha(i)));

alpha(i)=scan(var,i);

end;

drop i;

run;

proc print;run;

Haikuo

All Replies
Solution
‎11-05-2012 09:25 PM
Posts: 3,167

## Re: Working with character variables

Something like this?

data have;

input var \$char20.;

CARDS4;

A;B;C;D;A;B

A;B;C

B;A;D;D

B

J;K;C;K;J;K;A;B;C;D

;;;;

proc sql;

select (max(length(var))+1)/2 into :vn from have;quit;

data want;

array alpha(&vn) \$1.;

set have;

do i=1 to dim(alpha) until (missing (alpha(i)));

alpha(i)=scan(var,i);

end;

drop i;

run;

proc print;run;

Haikuo

Frequent Contributor
Posts: 93

## Re: Working with character variables

Wow! It worked beautifully! Thank you very much

I am jealous of your skills !

Super User
Posts: 10,761

## Re: Working with character variables

HaiKuo,

countw() is a good way.

do i=1 to countw(var,';');

🔒 This topic is solved and locked.