Skip to content

Instantly share code, notes, and snippets.

@barrucadu
Created March 5, 2020 12:50
Show Gist options
  • Save barrucadu/bf4994afd8fb5cb10fe57b3b8d465298 to your computer and use it in GitHub Desktop.
Save barrucadu/bf4994afd8fb5cb10fe57b3b8d465298 to your computer and use it in GitHub Desktop.
There are two different definitions of "isogram": this uses the definition "there are no duplicate characters"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare_chars(const void* ap, const void *bp) {
char a = *((char*) ap);
char b = *((char*) bp);
if (a > b) { return 1; }
if (a < b) { return -1; }
return 0;
}
bool is_isogram(char *word) {
for (size_t i = 0; i < strlen(word); i++) {
word[i] = (char) tolower(word[i]);
}
qsort(word, strlen(word), sizeof(char), *compare_chars);
for (size_t i = 1; i < strlen(word); i ++) {
if (word[i-1] == word[i]) {
return false;
}
}
return true;
}
int main(void) {
printf("enter a string to check: \n");
char *line = NULL;
size_t n = 0;
getline(&line, &n, stdin);
char delim = ' ';
char *tok = strtok(line, &delim);
while(tok != NULL) {
char *copy = strdup(tok);
if(is_isogram(copy)) {
printf("'%s' is an isogram.\n", tok);
return EXIT_SUCCESS;
}
free(copy);
tok = strtok(NULL, &delim);
}
free(line);
return EXIT_FAILURE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment