DATA Step, Macro, Functions and more

Concatenating strings using || operator

Reply
Occasional Contributor
Posts: 17

Concatenating strings using || operator

Hi Experts,

 

I am concatenating 2 strings using  || operator. Below is the question:

 

data sample;

length string1 $20.;

string1 = "Gurpreet";

string2 = "Kaur";

string1 = string1 || string2;

run;

 

My question is: The value of string1 in the dataset should be "GurpreetKaur". But the value is being shown as "Gurpreet" only. Please explain.

 

Thanks,

Gurpreet

Trusted Advisor
Posts: 1,131

Re: Concatenating strings using || operator

Please try with cats function, may the additional spaces are inhibiting from displaying the full name

 

data sample;
length string1 $20.;
string1 = "Gurpreet";
string2 = "Kaur";
string1 = cats(string1,string2);
run;

proc print;
run;
Thanks,
Jag
Super User
Super User
Posts: 7,413

Re: Concatenating strings using || operator

Yes, do remember that a string is an array of characters.  Where you define string1 to be $20 this means 20 boxes each with its own character.  So when you concatenate "Gurpreet            " with "Kaur", and put those 24 characters back into a variable which can only hold 20 characters the last four are dropped.

There are pletny of options to resolve this, for instance strip() each value:

string1=strip(string1)||strip(string2);

Or as @Jagadishkatam has given you, the cats() function would work well, note however you might want a space between so catx would be a better choice:

string1=catx(' ',string1,string2);

Ask a Question
Discussion stats
  • 2 replies
  • 186 views
  • 2 likes
  • 3 in conversation