How to Find All Position of Same Character In a String

Occasional Learner
Posts: 1

How to Find All Position of Same Character In a String

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!

Valued Guide
Posts: 537

Re: How to Find All Position of Same Character In a String

[ Edited ]
Posted in reply to chedrbalingit

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.

Super User
Posts: 9,794

Re: How to Find All Position of Same Character In a String

Posted in reply to chedrbalingit

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;
```
Super User
Posts: 10,844

Re: How to Find All Position of Same Character In a String

Posted in reply to chedrbalingit
```data _null_;
x='BAAABAABAB';
do i=1 to length(x);
if char(x,i)='B' then putlog 'Position:' i;
end;
run;

```
Super Contributor
Posts: 355

Re: How to Find All Position of Same Character In a String

Posted in reply to chedrbalingit

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;``````
Valued Guide
Posts: 537

Re: How to Find All Position of Same Character In a String

Posted in reply to user24feb

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.

Discussion stats
• 5 replies
• 638 views
• 0 likes
• 5 in conversation