📜  珀尔 | index()函数

📅  最后修改于: 2022-05-13 01:55:46.104000             🧑  作者: Mango

珀尔 | index()函数

此函数返回字符串(或文本)中给定子字符串(或模式)第一次出现的位置。我们可以指定起始位置。默认情况下,它从头开始搜索(即从索引零开始)。

示例 1:

#!/usr/bin/perl
  
# String from which Substring 
# is to be searched 
$string = "Geeks are the best";
  
# Using index() to search for substring
$index = index ($string, 'the');
  
# Printing the position of the substring
print "Position of 'the' in the string: $index\n";
输出:
Position of 'the' in the string: 10

示例 2:

#!/usr/bin/perl
  
# String from which Substring 
# is to be searched 
$string = "Geeks are the best";
  
# Defining the starting Index
$pos = 3;
  
# Using index() to search for substring
$index = index ($string, 'Geeks', $pos);
  
# Printing the position of the substring
print "Position of 'Geeks' in the string: $index\n";
输出:
Position of 'Geeks' in the string: -1

这里,在第二个示例中,位置设置为“3”,即开始搜索的起始索引是从第 3 个位置开始。因此,在字符串中找不到子字符串。