String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows:
- length()
- lc()
- uc()
- index()
- rindex()
length(): This function is used to find the number of characters in a string. This function returns the length of the string. Below are the programs to illustrate this method.
- Example 1:
my $s = "geeksforgeeks" ;
print ( length ( $s ), "\n" );
|
Output:
13
- Example 2:
my $s = "#$%HeLLo CSHARP &+#*" ;
print ( length ( $s ), "\n" );
|
Output:
19
lc(): This function return the lower case version of a string. Below are the programs to illustrate this method.
uc(): This function return the upper case version of a string. Below are the programs to illustrate this method.
index(): This method will search a substring from a specified position in a string and returns the position of the first occurrence of the substring in the string. If the position is omitted, it will search from the beginning of the string. This method will take the two parameters i.e. the original string and the substring that has to be searched.
Example :
use warnings;
use strict;
my $st = "GeeksforGeeks\n" ;
my $subs = "for" ;
my $r = index ( $st , $subs );
print ( qq\The substring $subs found at position $r in string $st\ );
|
Output:
The substring for found at position 5 in string GeeksforGeeks
rindex() This function is same as index() except it returns the last occurrence of text in a string. Also, a third parameter can be given which returns position before or at that location. It searches from the end of the string instead of from the beginning. Below are the programs to illustrate this method.
Example 1:
use warnings;
use strict;
my $st = "GeeksforGeeks\n" ;
my $subs = "for" ;
my $r = rindex ( $st , $subs );
print ( qq\The substring $subs found at position $r in string $st\ );
|
Output:
The substring for found at position 5 in string GeeksforGeeks
Example 2:
$p = rindex ( "GeeksForGFGGeeksgeeksforGFG" , "GFG" );
print "Founded position of GFG $p\n" ;
$p = rindex ( "GeeksForGFGGeeksgeeksforGFG" , "GFG" , $p -7);
print "Founded position of GFG $p\n" ;
|
Output:
Founded position of GFG 24
Founded position of GFG 8