Count the Number of Occurrences of a Character in a String

Count the number of occurrences of a character in a string

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

How do I count the number of occurrences of a char in a String?

My 'idiomatic one-liner' for this is:

int count = StringUtils.countMatches("a.b.c.d", ".");

Why write it yourself when it's already in commons lang?

Spring Framework's oneliner for this is:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

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

I have updated this answer. I like the idea of using a match better, but it is slower:

console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3

console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4

Count number of occurrences for each char in a string

This is really, really simple in JavaScript (or any other language that supports maps):

// The string
var str = "I want to count the number of occurrences of each char in this string";

// A map (in JavaScript, an object) for the character=>count mappings
var counts = {};

// Misc vars
var ch, index, len, count;

// Loop through the string...
for (index = 0, len = str.length; index < len; ++index) {
// Get this character
ch = str.charAt(index); // Not all engines support [] on strings

// Get the count for it, if we have one; we'll get `undefined` if we
// don't know this character yet
count = counts[ch];

// If we have one, store that count plus one; if not, store one
// We can rely on `count` being falsey if we haven't seen it before,
// because we never store falsey numbers in the `counts` object.
counts[ch] = count ? count + 1 : 1;
}

Now counts has properties for each character; the value of each property is the count. You can output those like this:

for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}

Count the number of occurrences of characters in a string?

You keep overriding the key with the latest count in that comprehension. You would have to rather update them by addition:

data = "a1a3b5a2c4b1"

counts = {}
i = iter(data)
for char, count in zip(i, i):
counts[char] = counts.get(char, 0) + int(count)

# {'a': 6, 'b': 6, 'c': 4}

The other natural util to handle counts is, well, a collections.Counter:

from collections import Counter

counts = Counter()

i = iter(data)
for char, count in zip(i, i):
counts.update(**{char: int(count)})

This also uses the "zip the same iterator" trick to produce chunks of 2. AS for turning these dictionaries into the desired string output:

"".join(f"{k}{v}" for k, v in counts.items())

count the number of occurrences of ( in a string

( is a special character. You need to escape it:

str_count(s,"\\(")
# [1] 3

Alternatively, given that you're using stringr, you can use the coll function:

str_count(s,coll("("))
# [1] 3

How would you count occurrences of a string (actually a char) within a string?

If you're using .NET 3.5 you can do this in a one-liner with LINQ:

int count = source.Count(f => f == '/');

If you don't want to use LINQ you can do it with:

int count = source.Split('/').Length - 1;

You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:

Your original = 12s

source.Count = 19s

source.Split = 17s

foreach (from bobwienholt's answer) = 10s

(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)

how to count occurrences of a character in a string without assigning the count explicitly to a variable, in perl

That trick

$dummy = () = $string =~ /[#]/g

works because the whole assignment-expression

() = EXPR

itself is in a scalar context, being assigned to a scalar ($dummy), so it returns the length of the would-be list which EXPR returns (it being in list context).

So impose the scalar context on it

say join('', '# occurs ', scalar( () = $string =~ /#/g ),' times');

I've shortened the string for easier reading, and employed say instead of print ... "\n".

See this page for more on () = EXPR and its context, and the links in it.

Not sure that this is really much prettier but it does what is asked.

But if you really always want just one character's count than tr does it much more nicely

print join('', '# occurs ', $string =~ tr/#//,' times in',"\n",$string,"\n",);

If one were to really just print then there is no need to form a string with join '' since print takes a list and effectively concatenates elements without anything in between, so joins them

say '# occurs ', scalar( () = $string =~ /#/g ), " times in\n", $string;

or, for a single character

say '# occurs ', $string =~ tr/#//, ' times in', "\n", $string;

(But I take it that the print is just an example for this question and that you really need a string...)

How to count number of occurrences of a certain char in string?

You can use this simple function:

function OccurrencesOfChar(const S: string; const C: char): integer;
var
i: Integer;
begin
result := 0;
for i := 1 to Length(S) do
if S[i] = C then
inc(result);
end;


Related Topics



Leave a reply



Submit