Simple Way to Count Character Occurrences 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", ".");

Simple way to count character occurrences in a string

public int countChar(String str, char c)
{
int count = 0;

for(int i=0; i < str.length(); i++)
{ if(str.charAt(i) == c)
count++;
}

return count;
}

This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.

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.)

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 nice and simple in JavaScript (or any other language that supports arbitrary key/value maps). And for key/value mapping, in JavaScript you have two options: objects and Map instances. In most cases where the keys are arbitrary as in this case, a Map is the better choice (more on MDN). Here's how that looks:

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

// A map for the character=>count mappings
const counts = new Map();

// Loop through the string...
for (const ch of str) {
// Get the count for it, if we have one; we'll get `undefined` if we don't
// know this character yet. Using nullish coalescing (`??`), we can turn
// that `undefined` into a `0`. (In obsolete environments that don't
// support nullish coalescing, for this use case we could use the logical
// OR operator [`||`] instead to use `0` instead of any falsy value, since
// A) `undefined` is falsy, and B) None of the count values we're tracking
// will be falsy because they're all non-zero. For some other use cases,
// we'd need to use a conditional testing `undefined` explicitly.)
const count = counts.get(ch) ?? 0;

// Add one and store the result
counts.set(ch, count + 1);
}

// Show the counts
for (const [ch, count] of counts) {
console.log(`"${ch}" count: ${counts.get(ch)}`);
}
.as-console-wrapper {
max-height: 100% !important;
}

How to count string occurrence in string?

The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:

var temp = "This is a string.";var count = (temp.match(/is/g) || []).length;console.log(count);


Related Topics



Leave a reply



Submit