program to disply sentance with n words as below in dataset variable ?
this
this is
this is sas
this is sas class.................n
How do you like this?
data test(drop=str);
str="We do not need to specify the length of a character variable if we are happy with the length it is given automatically";
do _n_=1 by 1 until(new=str);
new=catx(' ',new,scan(str,_n_));
output;
end;
run;
Interestingly, variable NEW seems to inherit the type and length of STR because of the UNTIL condition. Without that, it would be created as a numeric variable because of its uninitialized occurrence in the second argument of CATX. If it didn't occur there either, it would get a default length of $200 (see documentation of the CATX function).
Could you PLEASE be a little more elaborate about what you want to achieve?
this is the sentance r else you dont know the length of the sentance ...the words should display as 1st ,1st 2nd,1st 2nd 3rd ...........n
in a dataset with new variable
example
x='this is sas class'
the output should be like below
new
______
this
this is
this is sas
this is sas class
One way for that
data null;
length x $20;
retain x " ";
str="this is sas class";
do i = 1 to COUNTW(str) by 1;
x= strip(x) || " "||scan(str,i,' ') ;
output;
end;
run;
can we write the same program using other functions like anyspace , substr, compress,find functions ?n length shuld be the default length of the string to the new variable
Maybe we could, but why would we want to?
Mohamed's solution is looking fine, mine would have been almost identical.
because everytime we have to write length statement before if we increase that string word count......if string length is unkown then ??? that is my question
Setting the length is necessary. If you need to automate that, you can read the length of the input variable beforehand from sashelp.vcolumn and use that to set the length in the final data step.
How do you like this?
data test(drop=str);
str="We do not need to specify the length of a character variable if we are happy with the length it is given automatically";
do _n_=1 by 1 until(new=str);
new=catx(' ',new,scan(str,_n_));
output;
end;
run;
Interestingly, variable NEW seems to inherit the type and length of STR because of the UNTIL condition. Without that, it would be created as a numeric variable because of its uninitialized occurrence in the second argument of CATX. If it didn't occur there either, it would get a default length of $200 (see documentation of the CATX function).
This would work too
data have;;
str="this is sas class";
x=str;
do i = 1 to COUNTW(str) by 1;
if i=1 then x="";
x= strip(x) || " "||scan(str,i,' ') ;
output;
end;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.