Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of occurrences of a char in a string in C

Tags:

c

string

char

I have the string str

char *str = "100.10b.100.100"; 

I want to count the occurrences of '.' in str, preferably a one-liner. (If possible no loops)

My approach would be the standard strchr:

  int i = 0;   char *pch=strchr(str,'.');   while (pch!=NULL) {     i++;     pch=strchr(pch+1,'.');   } 
like image 656
Mike Avatar asked Nov 20 '10 23:11

Mike


People also ask

How do you count occurrences of a character in a string?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string. Remember, upper and lower cases are treated as different characters.

How do you count the number of occurrences of all characters in a string in C++?

The code snippet for this is given as follows. for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count; The program to find the frequency of all the alphabets in the string is given as follows.


2 Answers

Here's the way I'd do it (minimal number of variables needed):

for (i=0; s[i]; s[i]=='.' ? i++ : *s++); 
like image 142
R.. GitHub STOP HELPING ICE Avatar answered Oct 08 '22 17:10

R.. GitHub STOP HELPING ICE


OK, a non-loop implementation (and yes, it is meant as a joke).

size_t CountChars(const char *s, char c) {   size_t nCount=0;   if (s[0])   {     nCount += ( s[0]==c);     if (s[1])     {       nCount += ( s[1]==c);       if (s[2])       {         nCount += ( s[2]==c);         if (s[3])         {           nCount += ( s[3]==c);           if (s[4])           {             nCount += ( s[4]==c);             if (s[5])             {               nCount += ( s[5]==c);               if (s[6])               {                 nCount += ( s[6]==c);                 if (s[7])                 {                   nCount += ( s[7]==c);                   if (s[8])                   {                     nCount += ( s[8]==c);                     if (s[9])                     {                       nCount += ( s[9]==c);                       if (s[10])                       {                         /* too long */                         assert(0);                       }                     }                   }                 }               }             }           }         }       }     }   }   return nCount; } 
like image 23
Michael J Avatar answered Oct 08 '22 17:10

Michael J