Counting number of occurrences of a char in a string in C
NickName:Mike Ask DateTime:2010-11-21T07:10:52

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

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,'.');
  }

Copyright Notice:Content Author:「Mike」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/4235519/counting-number-of-occurrences-of-a-char-in-a-string-in-c

Answers
Steve Jessop 2010-11-20T23:31:02

If you're keen on a one-liner (well, two-):\n\nsize_t count = 0;\nwhile(*str) if (*str++ == '.') ++count;\n",


cdhowie 2010-11-20T23:15:44

I'd still throw this in a function, parametrizing the source string and the character to search for.\n\nint count_characters(const char *str, char character)\n{\n const char *p = str;\n int count = 0;\n\n do {\n if (*p == character)\n count++;\n } while (*(p++));\n\n return count;\n}\n",


Sanjeev 2016-06-04T06:46:26

//I guess it should work. One line and no loop.\n\nint countChar(char *s, char letter) {\n return ((*s) ? (((*s++ == letter)? 1:0)) + countChar (s, letter)): 0);\n}\n",


Michael J 2010-11-20T23:22:30

The only way to do it without a loop is recursion. The following is included for fun, but is NOT recommended as a solution:\n\nsize_t CountChars(char* s, char c)\n{\n return *s ? ((c==*s) + CountChars(s+1)) : 0;\n}\n",


user379888 2010-11-21T07:08:11

I dont like goto,still,\n\n int i=0,count=0;\n char *str = \"100.10b.100.100\";\n a:\n if(str[i]=='.')\n count++;\n i++;\n if(str[i])\n goto a;\n",


x y z 2012-10-27T21:52:31

everytime you run this code baby dijkstra cries :)\n\n 1\n 2\n 3\n 4 #include <ctype.h>\n 5 #include <stdio.h>\n 6 #include <stdlib.h>\n 7 #include <string.h>\n 8\n 9\n 10 size_t bytewise_pop_count(\n 11 unsigned char * bp, size_t l\n 12 ) {\n 13 if ( (bp) && (l) ) {\n 14 return bytewise_pop_count(bp+1, l-1) + (bp[0] ? 1 : 0);\n 15 }\n 16 return 0;\n 17 }\n 18\n 19 void mercilessly_complement_bytes(\n 20 unsigned char * bp, size_t l\n 21 ) {\n 22 /*\n 23 transform\n 24 0 -> 1\n 25 !0 -> 0\n 26 */\n 27 if ( (bp) && (l) ) {\n 28 bp[0] = bp[0] ? 0 : 1;\n 29 mercilessly_complement_bytes(bp+1, l-1);\n 30 }\n 31 }\n 32\n 33 void xor_bytes(\n 34 unsigned char * bp1, unsigned char * bp2, size_t l\n 35 ) {\n 36 /* stores result in bp2 */\n 37 if ( (bp1) && (bp2) && (l) ) {\n 38 bp2[0] ^= bp1[0];\n 39 xor_bytes(bp1+1, bp2+1, l-1);\n 40 }\n 41 }\n 42\n 43\n 44 int main(int argc, char * * argv) {\n 45 char c;\n 46 size_t count;\n 47 size_t l;\n 48 char * string;\n 49 char * t;\n 50\n 51 if (argc < 3) {\n 52 fprintf(stderr,\n 53 \"\\n\"\n 54 \"==> not enough arguments -- need char and string\\n\"\n 55 \"\\n\"\n 56 );\n 57 return EXIT_FAILURE;\n 58 }\n 59\n 60 c = argv[1][0];\n 61 string = argv[2];\n 62\n 63 if ( l = strlen(string) ) {\n 64 t = malloc(l);\n 65 memset(t, c, l);\n 66 xor_bytes(string, t, l);\n 67 mercilessly_complement_bytes(t, l);\n 68 count = bytewise_pop_count(t, l);\n 69 free(t);\n 70 } else {\n 71 count = 0;\n 72 }\n 73\n 74 if ( isprint(c) ) {\n 75 printf(\n 76 \"\\n\"\n 77 \"==> occurences of char ``%c'' in string ``%s'': %zu\\n\"\n 78 \"\\n\"\n 79 , c, string ? string : \"<NULL>\", count\n 80 );\n 81 } else {\n 82 printf(\n 83 \"\\n\"\n 84 \"==> occurences of char ``%hhu'' in string ``%s'': %zu\\n\"\n 85 \"\\n\"\n 86 , c, string ? string : \"<NULL>\", count\n 87 );\n 88 }\n 89 return EXIT_SUCCESS;\n 90 }\n",


R.. GitHub STOP HELPING ICE 2010-11-21T01:02:40

Here's the way I'd do it (minimal number of variables needed):\n\nfor (i=0; s[i]; s[i]=='.' ? i++ : *s++);\n",


WENDYN 2020-01-27T10:44:59

If you really want a one-liner:\n\n\nkeeping str intact (in case you want to use it later)\n\nfor(i = 0, c = 0; str[i] != '\\0'; (str[i] == '.')? c++: 0, i++);\nif you don't care about str variable\n\nfor(c = 0; *str != '\\0'; (*str == '.')? c++: 0, str++);\n\n\nadditionally you can subtract previous strlen to make it usable again\n\n\n\nbut as you can see, it's pretty ugly so I would advise doing something like this:\n\nfor(i = 0; str[i] != '\\0'; i++)\n{\n if(str[i] == '.')\n ++c;\n}\n\n\nor\n\nfor(c = 0; *str != '\\0'; str++)\n{\n if(*str == '.')\n ++c;\n}\n",


Michael J 2010-11-20T23:43:11

OK, a non-loop implementation (and yes, it is meant as a joke).\n\nsize_t CountChars(const char *s, char c)\n{\n size_t nCount=0;\n if (s[0])\n {\n nCount += ( s[0]==c);\n if (s[1])\n {\n nCount += ( s[1]==c);\n if (s[2])\n {\n nCount += ( s[2]==c);\n if (s[3])\n {\n nCount += ( s[3]==c);\n if (s[4])\n {\n nCount += ( s[4]==c);\n if (s[5])\n {\n nCount += ( s[5]==c);\n if (s[6])\n {\n nCount += ( s[6]==c);\n if (s[7])\n {\n nCount += ( s[7]==c);\n if (s[8])\n {\n nCount += ( s[8]==c);\n if (s[9])\n {\n nCount += ( s[9]==c);\n if (s[10])\n {\n /* too long */\n assert(0);\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return nCount;\n}\n",


tvanfosson 2010-11-20T23:16:33

Look, ma, no loops.\n\nint c = countChars( s, '.' );\n\nint countChars( char* s, char c )\n{\n return *s == '\\0'\n ? 0\n : countChars( s + 1, c ) + (*s == c);\n}\n\n\nBut, I'd actually use a loop, since that's the correct control structure to use.",


Fabian Giesen 2010-11-20T23:15:07

Without loops is going to be hard since there's no standard C library function that does this and you need to look at all chars :)\n\nI'll take the obvious solution:\n\nint i, count;\nfor (i=0, count=0; str[i]; i++)\n count += (str[i] == '.');\n\n\nFeel free to squeeze the two lines of actual code into one if you have to :)",


More about “Counting number of occurrences of a char in a string in C” related questions

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

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: in...

Show Detail

Counting Occurrences in char array

Write a function that accepts a character array as input, counts the number of occurrences for each character in the array, and outputs the result in format(eg {'c', 'e', 'e', 'e', 'a', 'q'} woul

Show Detail

Counting the number of occurrences of a string within a string

What's the best way of counting all the occurrences of a substring inside a string? Example: counting the occurrences of Foo inside FooBarFooBarFoo

Show Detail

Java Exception in Counting number of occurrences of character in a string

I am a java beginner and want to do some logic stuffs. I have started with a simple program (i.e) to find the total number of occurrences of a character in a string. But i ended up with this except...

Show Detail

Mutex - counting occurrences of a char in files using threads

Hi I am writing a code for counting the number of occurrences of a certain letter inside one or more files using thread. I have to use one thread for each file e use a mutex to modify the global to...

Show Detail

Count number of occurrences for each char in a string

I want to count the number of occurrences of each character in a given string using JavaScript. For example: var str = &quot;I want to count the number of occurrences of each char in this string&qu...

Show Detail

Counting the number of occurrences of a set of different substrings within a string in PostgreSQL

I have a database with lots of textual information, and I would like to count the number of times certain terms occur in a given text field. I know how to do this in Python, but as I am planning on

Show Detail

Find number of string separators in a string

I am using the following to find the number of separators in a string: char * string = "xi--len--xia" char * split_on = "--"; size_t len_joined_string = strlen(string); size_t len_split_on = strlen(

Show Detail

Number of occurrences in a string

I'm a total noob as far as visual basic goes. In class I need to do the following: "Write a program that requests a sentence from the user and then records the number of times each letter of the

Show Detail

number of occurrences in a string in C

Given a array string, I have to enter a word and find the occurrences of the word in the string, however I cannot enter the word for which I need to find the occurrence. I cannot use pointers as it...

Show Detail