Desktop productivity for business analysts and programmers

How to Find All Position of Same Character In a String

Reply
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!

Super Contributor
Posts: 406

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

[ Edited ]

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.

Esteemed Advisor
Esteemed Advisor
Posts: 7,232

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

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;
Grand Advisor
Posts: 9,584

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

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


Super Contributor
Posts: 336

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

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;
Super Contributor
Posts: 406

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

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.

Ask a Question
Discussion stats
  • 5 replies
  • 334 views
  • 0 likes
  • 5 in conversation