Desktop productivity for business analysts and programmers

How can I find the position of a character in a text.

Accepted Solution Solved
Reply
Contributor
Posts: 20
Accepted Solution

How can I find the position of a character in a text.

Hi All

Is it possible to find the position of a character in a text like these examples

TextNeed_Position_of_4Result
12341234444439
1112222223400120044444218

For the first example I need 3th 4 and the second one I need the second 4.


Accepted Solutions
Solution
‎08-14-2015 08:37 AM
Respected Advisor
Posts: 3,790

Re: How can I find the position of a character in a text.

Using FINDC you can search "Need Position of 4" number of times as follows.

data find;
   infile cards expandtabs;
  
input s :$30. o r;
   p=0;
  
do _n_ = 1 to o until(p eq 0);
      p = findc(s,'4',p+1);
      end;
  
drop startpos;
   cards;
123412344444   3  9
1112222223400120044444  2  18
1112222223400120044444  10 . 
;;;;
   run;
proc print;
  
run;

Capture.PNG

View solution in original post


All Replies
Super User
Super User
Posts: 7,727

Re: How can I find the position of a character in a text.

What is logic, i.e. why is it to find the first, or the second?  Post some test data in the form of a datastep, and required output, with an explanation of what you require.  If you want search functions (and you can find these out from the help documentation or google them): find, findw, findc, index etc.

Contributor
Posts: 65

Re: How can I find the position of a character in a text.

data Have;

input Text : $ 20.;

cards;

123412344444

1112222223400120044444

;

data Want;

set Have;

if _n_=1 then do;

Need_Position_of_4 = 3;

Result = findc(Text,'4',findc(Text,'4',index(Text,'4')+1)+1);

end;

else do;

Need_Position_of_4 = 2;

Result = findc(Text,'4',index(Text,'4')+1);

end;

run;

proc print ;run;

Solution
‎08-14-2015 08:37 AM
Respected Advisor
Posts: 3,790

Re: How can I find the position of a character in a text.

Using FINDC you can search "Need Position of 4" number of times as follows.

data find;
   infile cards expandtabs;
  
input s :$30. o r;
   p=0;
  
do _n_ = 1 to o until(p eq 0);
      p = findc(s,'4',p+1);
      end;
  
drop startpos;
   cards;
123412344444   3  9
1112222223400120044444  2  18
1112222223400120044444  10 . 
;;;;
   run;
proc print;
  
run;

Capture.PNG
Contributor
Posts: 20

Re: How can I find the position of a character in a text.

Thank you so much for your answer. it is very helpful.

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 477 views
  • 0 likes
  • 4 in conversation