Count the number of occurrences of a specific character in a string

From CodeCodex

Revision as of 14:54, 20 February 2011 by (Talk)

Related content:



 #include <algorithm>
 #include <string>
 using namespace std;
 int main() {
     string str("Count, the number,, of commas.");
     int count = count(str.begin(), str.end(), ',');


import std.string: count;
void main() {
    string s = "Count, the number,, of commas.";
    auto numberOfCommas = s.count(",");


count_chr(String, Chr) ->
    F = fun(X, N) when X =:= Chr -> N + 1;
           (_, N)                -> N
    lists:foldl(F, 0, String).

The use example

codex:count_chr("Count, the number,, of commas.", $,).


    s := "Count, the number,, of commas."
    n := 0
    for _, c := range s { 
        if c == ',' {


Implementation 1

This is the function:

String.prototype.count=function(s1) { 
	return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;

Use it like this:

// use like this 
test = "this, as you see, is a sentence, containing many ','s";
numberOfCommas = test.count(','); //4
// or 
numberOfSblank = test.count('s '); //2

Implementation 2

First, create a new function called replaceAll:

String.prototype.replaceAll=function(s1, s2) { 
	return this.replace(new RegExp(s1,"g"), s2);

Then you can use this function to count the occurrence of a specific character or string within another string. For example, this code counts the number of commas within a string. To count a different character, replace the comma in '[^,]' to another character, such as a lowercase x ('[^x]').

        numberOfCommas = text.replaceAll('[^,]','').length + 1;

Implementation 3

Another way to do it without RegExp:

String.prototype.count = function(char){
    return this.split(char).length-1;


There are multiple solutions. For such a low level task you should probably do a performance test to see which method is faster. For instance, regular expressions are very slow in java.

Implementation 1

This code will count the number of commas in a string.

	String s = "Count, the number,, of commas.";
	int numberOfCommas = s.replaceAll("[^,]","").length();

Implementation 2

public int count(String input, String countString){
  return input.split("\\Q"+countString+"\\E", -1).length - 1;

Implementation 3

public int count(String sourceString, char lookFor) {
    if (sourceString == null) {
        return -1;
    int count = 0;
    for (int i = 0; i < sourceString.length(); i++) {
        final char c = sourceString.charAt(i);
        if (c == lookFor) {
    return count;


$count = () = $string =~ /colou?r/g; # count the number of  colours (and colors).
$count = $string =~ tr/,//; # count the number of commas. this does not modify the string in any way


This code will count the number of commas in a string.

s = "Count, the number,, of commas."
print s.count(",")


PHP has a built-in function for this called substr_count.

$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);

// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);

// prints only 1, because it doesn't count overlapped subtrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');


s = "Count, the number,, of commas."
puts s.count(",")


set s "Count, the number,, of commas."
puts [expr {[llength [split $s ","]] - 1}]


count() {
	local string char
	string="Count, the number,, of commas."
	print ${(c)#char}	

Other titles

This section is to help the Shopobot search engine find this page. Feel free to add an alternate description of this page's content.

  • string char count
  • number of occurrences in a string
  • character count for strings