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,'.'); }
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.
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.
Here's the way I'd do it (minimal number of variables needed):
for (i=0; s[i]; s[i]=='.' ? i++ : *s++);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With