## find first location of character in string

Regular Contributor
Posts: 199

# find first location of character in string

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

Super User
Posts: 9,790

## Re: find first location of character in string

```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;```

Posts: 4,776

## Re: find first location of character in string

@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;``````
Super User
Posts: 9,790

## Re: find first location of character in string

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.

Posts: 4,776

## Re: find first location of character in string

@RW9

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

Super User
Posts: 9,790

## Re: find first location of character in string

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

PROC Star
Posts: 269

## Re: find first location of character in string

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.

Posts: 4,776

## Re: find first location of character in string

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.

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