BookmarkSubscribeRSS Feed
Ronein
Onyx | Level 15

Hello

I want to find first location of character in string.

Lets say I have the following data.

Vector='0,0,5,11,9,10'

I want to find the first location (after comma) where the number is different than 0.

In this case the answer is  3  because the third argument in vector has value different than 0.

 

How can I calculate it in SAS  please?

 

 

 

thanks

Ronein

7 REPLIES 7
RW9
Diamond | Level 26 RW9
Diamond | Level 26
data want (drop=i);
  Vector='0,0,5,11,9,10';
  do i=1 to countw(vector,',');
    if input(scan(vector,i,','),best.) > 0 and word = . then word=i;
  end;
run;

 

 

 

Patrick
Opal | Level 21

@RW9's code with a tweak to stop looping once a word has been found.

data want (drop=_:);
  Vector='0,0,5,11,9,10';
  _n=countw(vector,',');
  do _i=1 to _n;
    if input(scan(vector,_i,','),best.) > 0 then
      do;
        word=_i;
        leave;
      end;
  end;
run;
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Quite true, but then you would only need:

data want;
  vector='0,0,5,11,9,10';
  do word=1 to countw(vector,',');
    if input(scan(vector,word,','),best.) > 0 then leave;
  end;
run;

As word gets incremented up to the point where the loop is exited.

Patrick
Opal | Level 21

@RW9

And what's the value of Word if the condition never gets True?

RW9
Diamond | Level 26 RW9
Diamond | Level 26

True, I had assumed there would always be one non-zero.  

s_lassen
Meteorite | Level 14

This is one of the occasions where PRX is really good:

data want;
  Vector='0,0,5,11,9,10';
  pos=prxmatch('/\b[1-9]/',Vector);
run;

A short explanation of the search string: \b means a word boundary (could be your comma, or the beginning of the string), [1-9] means one of the digits 1 to 9. If there is no match, the function returns 0.

Patrick
Opal | Level 21

@s_lassen wrote:

This is one of the occasions where PRX is really good:

data want;
  Vector='0,0,5,11,9,10';
  pos=prxmatch('/\b[1-9]/',Vector);
run;

A short explanation of the search string: \b means a word boundary (could be your comma, or the beginning of the string), [1-9] means one of the digits 1 to 9. If there is no match, the function returns 0.


@s_lassen

...except that it returns 5 instead of 3. The OP asks for the number of the Word (3rd word) and not the start position in the string.

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 7 replies
  • 2338 views
  • 4 likes
  • 4 in conversation