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 argumentsstart
andend
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", ".");
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
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.
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]);
}
Is there a better way to count occurrence of char in a string?
Counting the occurences of a character in a string can be performed with one line in Perl (as compared to your 4 lines). There is no need for a sub (although there is nothing wrong with encapsulating functionality in a sub). From perlfaq4 "How can I count the number of occurrences of a substring within a string?"
use warnings;
use strict;
my $str = "ru8xysyyyyyyysss6s5s";
my $char = "y";
my $count = () = $str =~ /\Q$char/g;
print "count<$count> of <$char> in <$str>\n";
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;
Count the occurrence of characters in a string
so i figured out how to do it without using sets and counters.
S = (input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
L = []
#counts the occurrence of characters in a string.
#then puts them in a list
for char in S:
if char in alpha:
count = S.count(char)
L.append(char)
L.append(count)
#turns list into a nested list
L2 = []
i = 0
while i <len(L):
L2.append(L[i:i+2])
i += 2
#checks that the lists dont appear more than once
L3 = []
for i in L2:
if i not in L3:
L3.append(i)
# print out the letters and count of the letter
for i,k in L3:
print(i,k)
might be long but it works. would like your opinion on it?
Related Topics
Why Is Processing a Sorted Array Faster Than Processing an Unsorted Array
Signing Pdfs on a Server Document Using a Signature from the User
Why Is It Considered a Bad Practice to Omit Curly Braces
How to Simulate the C++ 'Friend' Concept in Java
How to Round Up the Result of Integer Division
Is Short Circuit Evaluation Guaranteed in C++ as It Is in Java
Calling a Java Method from C++ in Android
How to Send Http Request in Java
Converting HTML to Pdf Using Itext
How to "Scan" a Website (Or Page) For Info, and Bring It into My Program
Round a Double to 2 Decimal Places
Android Studio Gradle Project "Unable to Start the Daemon Process /Initialization of Vm"
Integer Division: How to Produce a Double
How to Find the Caller of a Method Using Stacktrace or Reflection
Why Is 128==128 False But 127==127 Is True When Comparing Integer Wrappers in Java