← Back to Perl Course | Chapter 3: Strings | Lesson 4 of 7

length, substr और index

आप एक string measure कर सकते हैं, इससे pieces काट सकते हैं, और एक piece कहाँ शुरू होता है ढूंढ सकते हैं।

length, substr, और index

length characters की संख्या return करता है, substr एक string के हिस्से extract या replace करता है, और index और rindex एक substring की position ढूंढते हैं। Positions 0 से शुरू होती हैं, और जब कुछ न मिले index -1 return करता है। substr को assign भी किया जा सकता है, या एक चौथा argument दिया जा सकता है, string का हिस्सा replace करने के लिए।

Note: substr में एक negative offset string के अंत से count करता है।

उदाहरण: length, substr and index

perl
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
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह उम्मीद करना कि शुरुआत में एक match के लिए index 1 return करेगा
  2. यह भूल जाना कि जब कोई match न हो index -1 return करता है
  3. यह मान लेना कि एक replacement वाला substr removed part की बजाय नई string return करता है
चैप्टर सारांश
  • length characters count करता है
  • substr(str, offset, length) text extract करता है
  • index और rindex positions या -1 return करते हैं
  • substr text replace कर सकता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.