length, substr and index
You can measure a string, cut pieces out of it and find where a piece begins.
In this page:
length, substr and index
length returns the number of characters, substr extracts or replaces part of a string, and index and rindex find the position of a substring. Positions start at 0, and index returns -1 when nothing is found. substr can also be assigned to, or given a fourth argument, to replace part of the string.
Note:
A negative offset in substr counts from the end of the string.
Example: length, substr and index
use strict;
use warnings;
my $s = "Hello, Perl world";
print "length: ", length($s), "\n";
print "substr: ", substr($s, 7, 4), "\n";
print "from end: ", substr($s, -5), "\n";
print "index of 'Perl': ", index($s, "Perl"), "\n";
print "index of 'xyz': ", index($s, "xyz"), "\n";
print "rindex of 'o': ", rindex($s, "o"), "\n";
substr($s, 0, 5) = "Howdy";
print "after assignment: $s\n";
my $removed = substr($s, 7, 4, "PERL");
print "removed '$removed', now: $s\n";
# Output:
# length: 17
# substr: Perl
# from end: world
# index of 'Perl': 7
# index of 'xyz': -1
# rindex of 'o': 13
# after assignment: Howdy, Perl world
# removed 'Perl', now: Howdy, PERL world
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting index to return 1 for a match at the start
- Forgetting that index returns -1 when there is no match
- Assuming substr with a replacement returns the new string instead of the removed part
Chapter Summary
- length counts characters
- substr(str, offset, length) extracts text
- index and rindex return positions or -1
- substr can replace text
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: