Perl | index() Function
Last Updated :
06 Mar, 2023
This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero).
Syntax: # Searches pat in text from given index index(text, pat, index) # Searches pat in text index(text, pat) Parameters:
- text: String in which substring is to be searched.
- pat: Substring to be searched.
- index: Starting index(set by the user or it takes zero by default).
Returns: -1 on failure otherwise Position of the matching string.
Example 1:
Perl
#!/usr/bin/perl
$string = "Geeks are the best";
$index = index ( $string , 'the' );
print "Position of 'the' in the string: $index \n";
|
Output:
Position of 'the' in the string: 10
Example 2:
Perl
#!/usr/bin/perl
$string = "Geeks are the best";
$pos = 3;
$index = index ( $string , 'Geeks' , $pos );
print "Position of 'Geeks' in the string: $index \n";
|
Output:
Position of 'Geeks' in the string: -1
Here, in the second example the position is set to ‘3’, i.e. the starting index from where searching is to begin is from 3rd position. Hence, the substring is not found in the String.
Example – 3: Here we will see what will happen if the string/character we are trying to find is present more than once in the real string.
Perl
#!/usr/bin/perl
$string = 'Geeks for Geeks' ;
$char = 'e' ;
$res = index ( $string , $char );
print ( "Position of $char is : $res\n" );
|
Output –
Now as we can see it returned the output as 1 which is the first occurrence of ‘e’. If we have the required character present more than once in our string, index will return the first occurrence by default.
Example – 4 : Here we will see how we can get all the occurrences of a character in the original string.
Perl
#!/usr/bin/perl
my $string = 'Geeks for Geeks' ;
my $char = 'e' ;
my $start = 0;
my $res = index ( $string , $char , $start );
while ( $res != -1 ) {
print ( "Occurence of $char at $res\n" );
$start = $res +1;
$res = index ( $string , $char , $start );
}
|
Output –
Share your thoughts in the comments
Please Login to comment...