Count the number of occurrences of a specific character in a string
From CodeCodex
| Related content: |
|
Contents |
Implementations
C++
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str("Count, the number,, of commas.");
int count = count(str.begin(), str.end(), ',');
}
D
import std.string: count;
void main() {
string s = "Count, the number,, of commas.";
auto numberOfCommas = s.count(",");
}
Erlang
-module(codex).
-export([count_chr/2]).
count_chr(String, Chr) ->
F = fun(X, N) when X =:= Chr -> N + 1;
(_, N) -> N
end,
lists:foldl(F, 0, String).
The use example
codex:count_chr("Count, the number,, of commas.", $,).
Go
s := "Count, the number,, of commas."
n := 0
for _, c := range s {
if c == ',' {
n++
}
}
fmt.Println(n)
Haskell
countOfElem elem list = length $ filter (\x -> x == elem) list
or more point-free
countOfElem elem = length . filter (==elem)
In ghci:
*Main> countOfElem 'i' "Veni vidi vici" 5
JavaScript
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;
}
Implementation 4
Without functions and without RegExp
('ab,cd,ef'.split(',').length - 1)
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.
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) {
count++;
}
}
return count;
}
Implementation 4
public static int count(String word, Character ch)
{
int pos = word.indexOf(ch);
return pos == -1 ? 0 : 1 + count(word.substring(pos+1),ch);
}
Perl
$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
Python
This code will count the number of commas in a string.
s = "Count, the number,, of commas."
print s.count(",")
PHP
PHP has a built-in function for this called substr_count.
<?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'); ?>
Ruby
s = "Count, the number,, of commas."
puts s.count(",")
Tcl
set s "Count, the number,, of commas."
puts [expr {[llength [split $s ","]] - 1}]
Zsh
count() {
local string char
string="Count, the number,, of commas."
char=${string//[^,]/}
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