DATA Step, Macro, Functions and more

substr

Reply
Occasional Contributor
Posts: 9

substr

 

can you plz explain how come the length of variable sec is 25 ? 

 

data test;
first = 'ipswich, england';
sec = substr(first,1,7)!!','!!'England';
run;

Super User
Super User
Posts: 9,599

Re: substr

It is because you have not explicitly set any lengths SAS uses its defaults.

So:
first is set to 16 as that is the length of the first string applied to it.

Then the substr is called, and logically the maximum value that this can return is length of first, + 1 for the comma, + length of string England = 24, so sec is set to be length 24, so that it can fully cover anything the substr()+,+England can return.

 

Solution, always set lengths yourself, don't let the software try to guess for you.

 

Super User
Posts: 6,785

Re: substr

The key to understanding why is to simplify the problem:

 

sec = substr(first, 1, 7);

 

Here, the length of SEC is 16, the same as the length of FIRST.  The reason:  the third parameter to SUBSTR does not have to be hard-coded.  It can be an expression, calculated based on variables within the incoming data.  So when SAS sees SUBSTR, it doesn't even look at the third parameter.  Rather, it notes that it is taking some portion of FIRST.  It might be taking the whole thing.  So to be safe, SAS assigns SEC the same length as FIRST.

 

When you add ", England" you just have to add that many characters to the length of FIRST.

Super User
Posts: 10,280

Re: substr


@sanyam13 wrote:

 

can you plz explain how come the length of variable sec is 25 ? 

 

data test;
first = 'ipswich, england';
sec = substr(first,1,7)!!','!!'England';
run;


SAS makes guesses about the required length for a new variable, depending on the length of variables and literals used. To prevent such guesses from happening (as they usually don't end up with the desired result), it is best practice to use the length statement.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Ask a Question
Discussion stats
  • 3 replies
  • 69 views
  • 2 likes
  • 4 in conversation