fork(4) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <stdbool.h>
  7. #include <stddef.h>
  8.  
  9. size_t duplicate_count(const char *text);
  10. char *myStrdup(const char *text);
  11.  
  12. int main(void)
  13. {
  14. char input[1023];
  15. printf("Enter a string of letters and/or numbers "
  16. "without any space and press ENTER: ");
  17. if ((fgets(input, 1023, stdin)) != NULL)
  18. {
  19. printf("Total number of duplicates: %zu\n"
  20. , duplicate_count(input) );
  21. }
  22.  
  23. return 0;
  24. }
  25.  
  26. size_t duplicate_count(const char *text)
  27. {
  28. char *input = NULL;
  29. char *distincts = NULL;
  30. size_t lengthOfInput= 0;
  31. size_t lengthOfDistincts = 1;
  32. size_t count = 0;
  33. size_t dups = 0;
  34.  
  35. input = myStrdup(text);
  36. input[strlen(input) - 1] = '\0';
  37. lengthOfInput = strlen(input);
  38. for (size_t i = 0; i < lengthOfInput; i++)
  39. {
  40. if (isalpha(input[i]) && isupper(input[i]))
  41. {
  42. input[i] = tolower(input[i]);
  43. }
  44. }
  45. distincts = realloc(distincts, lengthOfDistincts);
  46. assert(distincts);
  47. distincts[0] = input[0];
  48. distincts[lengthOfDistincts++] = '\0';
  49.  
  50. for (size_t i = 1; i <= lengthOfInput; i++)
  51. {
  52. if (distincts[0] == input[i])
  53. {
  54. count = 1;
  55. }
  56. else
  57. {
  58. size_t found = 0;
  59. for (size_t j = 0; j < lengthOfDistincts - 1; j++)
  60. {
  61. if (input[i] == distincts[j])
  62. {
  63. found++;
  64. }
  65. }
  66. if (!found)
  67. {
  68. distincts = realloc(distincts, lengthOfDistincts + 1);
  69. distincts[lengthOfDistincts - 1] = input[i];
  70. distincts[lengthOfDistincts++ ] = '\0';
  71. }
  72. }
  73. }
  74. if (count) { dups++; }
  75.  
  76.  
  77. for (size_t i = 1; i < lengthOfDistincts; i++)
  78. {
  79. size_t occurance = 0;
  80. for (size_t j = 0; j < lengthOfInput; j++)
  81. {
  82. if (distincts[i] == input[j])
  83. {
  84. occurance++;
  85. }
  86. }
  87. if (occurance > 1) { dups++; }
  88. }
  89. free(input);
  90. free(distincts);
  91.  
  92. return dups;
  93. }
  94.  
  95. char *myStrdup(const char *text)
  96. {
  97. static char *replicate = NULL;
  98. size_t lengthOfText = strlen(text) + 1;
  99. replicate = realloc(replicate, lengthOfText);
  100. if (replicate == NULL)
  101. {
  102. return (char *) NULL;
  103. }
  104.  
  105. return (char *)memcpy(replicate, text, lengthOfText);
  106. }
  107.  
Success #stdin #stdout 0s 5672KB
stdin
abcdea
stdout
Enter a string of letters and/or numbers without any space and press ENTER: Total number of duplicates: 0