Hi,
Is there a function that determines the position of the same character in a string. For example, I want to know the position of the characters 'B' in a string BAAABAABAB. I am expecting the results: 1,5,8,and 10.
Thanks!
The FIND() function is perfectly suited for this because it allows for a start position inside the searched string:
data _null_;
string='ABAAABAABAB';
pos = 0;
do until (pos = 0);
pos = find (string, 'B', pos+1);
if pos>0 then put pos=;
end;
run;
Hope this helps,
- Jan.
For example:
data want (drop=i); length result $200; val="BAAABAABAB"; do i=1 to lengthn(val); if char(val,i)="B" then result=catx(",",result,strip(put(i,best.))); end; run;
data _null_; x='BAAABAABAB'; do i=1 to length(x); if char(x,i)='B' then putlog 'Position:' i; end; run;
I think there is room for interpretation what exactly you would like to do:
%Let Max_Len=20; *!!;
Data A;
Attrib Txt Length=$&Max_Len.;
Txt='AABBBBAAAAAABBABAB'; Output;
Txt='GDFSCCCDD'; Output;
Txt='DFDCZ'; Output;
Run;
Data _NULL_;
Length Letters $300.;
Letters='Capital_A';
Do i=2 To 26;
Letters=Catt(Letters,' Capital_',Byte(i+64));
End;
Call SymputX('Letters',Letters);
Run;
Data Want;
Set A;
Array C_[*] $%Eval(&Max_Len*4) &Letters. ;
Do i=1 To &Max_Len.;
dummy=Substr(Txt,i,1);
ascii=Rank(dummy);
If ascii ne 32 Then Do;
If not Missing (C_[ascii-64]) Then C_[ascii-64]=Catt(C_[ascii-64],', ',Put(i,Best4.));
Else C_[ascii-64]=Trim(Put(i,Best4.));
End;
End;
Do i=1 To Dim(C_);
Character=VName(C_[i]);
Positions=C_[i];
If not Missing (Positions) Then Output;
End;
Drop &Letters. dummy ascii i;
Run;
Nice piece of code, @user24feb. Would you like to share what interpretation your solution is based upon?
My native language has no direct translation of "convoluted". I miss that.
Regards,
- Jan.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
Check out this tutorial series to learn how to build your own steps in SAS Studio.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.