icon Top 9 categories map      RocketAware > Perl >

How can I count the number of occurrences of a substring within a string?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.


Search Perl pages


By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Integer, Floating point, Matrix, Statistics, Boolean, ...

Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...


How can I count the number of occurrences of a substring within a string?

There are a number of ways, with varying efficiency: If you want a count of a certain single character (X) within a string, you can use the tr/// function like so:

    $string = "ThisXlineXhasXsomeXx'sXinXit":
    $count = ($string =~ tr/X//);
    print "There are $count X charcters in the string";

This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a larger string, tr/// won't work. What you can do is wrap a while() loop around a global pattern match. For example, let's count negative integers:

    $string = "-9 55 48 -2 23 -76 4 14 -44";
    while ($string =~ /-\d+/g) { $count++ }
    print "There are $count negative numbers in the string";

Source: Perl FAQ: Data Manipulation
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How do I capitalize all the words on one line?

Previous: How do I change the Nth occurrence of something?

(Corrections, notes, and links courtesy of RocketAware.com)

[Overview Topics]

Up to: NUL Terminated String processing

Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq4/How_can_I_count_the_number_of_oc.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments