You could use memchr to find if a character occurs in the remainder of the string, replicating the functionality of in in Python, but algorithmically, you're better off sorting the string first and then looping over it, because then all repeated characters will be contiguous.
Caveat: I'm not testing to ensure strdup succeeded in the following.
#include <stdlib.h> #include <string.h> #include <stdio.h> int compare_chars(const void *a, const void *b) { char c = *(char *)a; char d = *(char *)b; return c == d ? 0 : c < d ? -1 : 1; } int main(void) { const char *s = "dacabcabcff"; char *s2 = strdup(s); qsort(s2, strlen(s2), 1, compare_chars); char last_char = '\0'; for (size_t i = 0; s2[i]; i++) { if (s2[i] == last_char) { printf("%c\n", s2[i]); // Skip to the next unique character // to avoid printing repeated characters // more than once. while (s2[i] && s2[i] == last_char) i++; } last_char = s2[i]; } free(s2); }
Of course, the table mentioned by @SomeProgrammerDude in comments scales better as it's an O(n) solution rather than O(n * log n), but it does not scale to data sets which involve much larger possible values.
Consider how this would work if we had an array of 32-bit integers. The table to hold them would have to hold ~4 billion values.
A naive approach would simply iterate over the rest of the string to determine if the same character occurs again.
int main(void) { const char *s = "dacabcabcff"; size_t len = strlen(s); for (size_t i = 0; i < len - 1; i++) { int found_again = 0; for (size_t j = i + 1; !found_again && j < len; j++) { if (s[i] == s[j]) { found_again = 1; } } if (found_again) { printf("%c\n", s[i]); } } }
This poses a problem as it has quadratic or O(n^2) runtime complexity, but also because it may print the same character multiple times.
We could write code to remove that character from the remainder of the string, but that adds further work to a solution which is already working too hard.
E.g.
int main(void) { // Not a string literal so it can be modified. char s[] = "dacabcabcff"; for (size_t i = 0; i < strlen(s) - 1; i++) { int found_again = 0; for (size_t j = i + 1; !found_again && j < strlen(s); j++) { if (s[i] == s[j]) { found_again = 1; } } // Avoiding wrapping everything after this // in a conditional block. if (!found_again) continue; printf("%c\n", s[i]); // Eliminate s[i] from the rest of the string. size_t k = i+1; for (size_t j = i+1; j < strlen(s); j++) { if (s[j] != s[i]) s[k++] = s[j]; } s[k] = '\0'; } }
char substring[] ={0};the size of your array is 1, you don't have space to storencharacters in it.there is not equivalent of if not in in C,there isif (!strchr(char_dict, letter))"Follow"... Are both theoandlcharacters repeated? Only thel?insuggest that the o's in "follow" would be considered repeated. As does the output from that Python snippet.