Using strchr() to count occurrences of a character in a string
Your loop is always looking from the beginning of pString
, and is always finding the first 'e' over and over again.
If you declare char* pTemp = pString;
then you can iterate a little differently (I pasted the wrong version earlier, sorry!):
char* pTemp = pString;
while(pTemp != NULL)
{
pTemp = strchr(pTemp, c);
if( pTemp ) {
pTemp++;
count++;
}
}
This forces pTemp
to point just after the character you just found before looking for the next one.
It would be easier to just do:
char* pTemp = pString;
while( *pTemp )
if( *pTemp++ == c) count++;
Okay, after thinking about it, even after you already have this working, I changed the inner loop to a form I am more happy with:
while( (pTemp = strchr(pTemp, c)) != NULL) {
count++;
pTemp++;
}
Count occurrences of character in string c++?
Your code is counting characters when it should be counting substrings instead, eg:
#include <iostream>
#include <string>
#include <conio.h>
int main()
{
std::string a, b;
int count = 0;
std::cout << "Enter 1st String: ";
std::getline(std::cin, a);
std::cout << "Enter 2nd String: ";
std::getline(std::cin, b);
std::string::size_type i = a.find(b);
while (i != std::string::npos)
{
++count;
i = a.find(b, i+b.length());
}
std::cout << "Output: " << count;
getch();
return 0;
}
Count occurrences of a string character in an array
I did a bit of tweaking of your code so that the parameters in your function align with the parameters passed when your function is called. Following is an example of what your code might look like in order to count characters.
#include <stdio.h>
#include <stdlib.h>
int count(char letter, char* array, int number) /* Made second parameter a character array in lieu of an integer array */
{
int sum= 0;
int i;
for(i = 0; i < number; ++i)
{
if(array[i] == letter)
++sum;
}
return sum;
}
int main()
{
char array[] = { 'A','B','B','C'};
int number= sizeof(array) / sizeof(char) ;
printf("Count: %d\n",count('A', array, number)); /* Changed from string constant "A" to character 'A' */
return 0;
}
First off, you appear to want to send a character as your first parameter to your function. In your original code you were actually sending a string constant as "A" was enclosed in double quotes and not single quotes. The second parameter is a character array (aka, a string). Therefore, in your function definition the second parameter there needs to be a character array and not an integer array. Characters take up one or two bytes of memory depending upon the system, and integers "usually" take up four bytes of memory. So there would be a mismatch in attempting to check out array values.
Using your revised function to produce output for a "printf" call, I received the following output on my terminal.
Count: 1
So probably the biggest takeaway from this is that characters (e.g. 'A') are different from string constants (e.g. "A"), and characters, even though they equate to an integer value, utilize a smaller chunk of memory than do integers.
Hope that helps.
Regards.
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 can I count the number of occurrences of the character '/' in a C string?
strchr
would make a smaller loop:
ptr = str;
while ((ptr = strchr(ptr '/')) != NULL)
count++, ptr++;
I should add that I don't endorse brevity for brevity's sake, and I'll always opt for the clearest expression, all other things being equal. I do find the strchr
loop more elegant, but the original implementation in the question is clear and lives inside a function, so I don't prefer one over the other, so long as they both pass unit tests.
Related Topics
Friend and Inline Method, What's the Point
What's the Meaning of * and & When Applied to Variable Names
How to Parse Date/Time from String
Why User-Defined Move-Constructor Disables the Implicit Copy-Constructor
C++ Boost: Undefined Reference to Boost::System::Generic_Category()
Gcc C++ "Hello World" Program -> .Exe Is 500Kb Big When Compiled on Windows. How to Reduce Its Size
How to Embed a File into an Executable
C++: Argument Passing "Passed by Reference"
What's This C++ Syntax That Puts a Brace-Surrounded Block Where an Expression Is Expected
Calling Virtual Function from Destructor
Variable Assignment in an "If" Condition
Template Deduction for Function Based on Its Return Type