Count the number of occurrences of a specific character in a string
From CodeCodex
Contents |
[edit] Implementations
[edit] C++
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str("Count, the number,, of commas.");
int count = count(str.begin(), str.end(), ',');
}[edit] D
import std.string: count;
void main() {
string s = "Count, the number,, of commas.";
auto numberOfCommas = s.count(",");
}
[edit] JavaScript
//create this function
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
// use like this
test = "this, as you see, is a sentence, containing many ','s";
numberOfCommas = test.count(','); //4
// or
numberOfSblank = test.count('s '); //2
// Thanks to code below, above does job better
// This also finds number of any number of strings
// hasan at f p m 3 dot c o m
I think above code seems easier to implement than below. Hasan Cosgun
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;
Another way to do it without RegExp:
String.prototype.count = function(char){
return this.split(char).length-1;
}
[edit] Java
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.
This code will count the number of commas in a string.
String s = "Count, the number,, of commas.";
int numberOfCommas = s.replaceAll("[^,]","").length();
Also we can do like below:
public int count(String input, String countString){ return input.split("\\Q"+countString+"\\E", -1).length - 1; }
Another solution is:
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) { count++; } } return count; }
[edit] Perl
$count = () = $string =~ /colou?r/g; # count the number of colours (and colors).
[edit] Python
This code will count the number of commas in a string.
s = "Count, the number,, of commas."
print s.count(",")
[edit] PHP
PHP has a built-in function for this.
see http://php.net/substr_count
substr_count ( string $haystack , string $needle [, int $offset=0 [, int $length ]] ) Returns: INT
<?php $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'); ?>
[edit] Ruby
s = "Count, the number,, of commas." puts s.count(",")
[edit] Zsh
count() {
local string char
string="Count, the number,, of commas."
char=${string//[^,]/}
print ${(c)#char}
}

