go ahead... be a heretic PerlMonks

### finding the position of a particular character in a string

by deep3101 (Acolyte)
 on Oct 06, 2011 at 02:46 UTC Need Help??
deep3101 has asked for the wisdom of the Perl Monks concerning the following question:

I wanted to know if there is any method to find the position of occurance of a particular character in a string, the character can ofcourse occur more than once.

```\$a="THE FOOD IS DELICIOUS";

Then if I want the position of "O" so I should get 6,7,19 or 5,6,18 will work too. But don't want to use arrays and conventional

\$pos++;

with for loop as the string is too big and lot of comparisons need to be done.

Replies are listed 'Best First'.
Re: finding the position of a particular character in a string
by NetWallah (Canon) on Oct 06, 2011 at 04:59 UTC
```>perl -e "my \$a=q|THE FOOD IS DELICIOUS|;for(my \$x=-1;(\$x=index(\$a,qq|
+O|,\$x+1))>=0;){print qq|\$x\n|}"
5
6
18

"XML is like violence: if it doesn't solve your problem, use more."

Re: finding the position of a particular character in a string
by keszler (Priest) on Oct 06, 2011 at 03:29 UTC
```perl -E'
\$a="THE FOOD IS DELICIOUS";
\$srch="O";
push @i,index(\$a,\$srch,\$i[-1]+1) for \$a=~/\$srch/g;
\$" = ",";
say "@i";
'

5,6,18

Searching twice is expensive and unnecessary:

```\$a="THE FOOD IS DELICIOUS";;
\$p=0; @p=();

push @p, \$p-1 while \$p = 1+index \$a, 'O', \$p;

print @p;;
5 6 18

Or:

```\$a="THE FOOD IS DELICIOUS";;
@p=();
push @p, \$-[0] while \$a =~ m[O]g;;

print @p;;
5 6 18

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
Re: finding the position of a particular character in a string
by ww (Archbishop) on Oct 06, 2011 at 08:28 UTC

How did you arrive at "6,7,18 or 5,6,17" as acceptable results?

123456789012345678901 # one-based - 6,7,19
THE FOOD IS DELICIOUS
012345678901234567890 # zero-based - 5,6,18

Instead of finding out my error you might as well have responded with a solution as others have. And from my end I extend apology for error in counting.

Instead of finding out my error you might as well have responded with a solution as others have.

Re: finding the position of a particular character in a string
by Anonymous Monk on Oct 06, 2011 at 03:18 UTC

Create A New User
Node Status?
node history
Node Type: perlquestion [id://929912]
Approved by keszler
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2018-06-19 21:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Should cpanminus be part of the standard Perl release?

Results (115 votes). Check out past polls.

Notices?