Last active
October 15, 2021 07:12
-
-
Save dmgerman/d06c11864a9aa431055b6e1f2ba2df21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#include <string.h> | |
#include <ctype.h> | |
// return a pointer to the first character that does not satisfy the function f | |
// or a pointer to the end of the string | |
char *skip(char *st, int (f)(char)) | |
{ | |
assert(st != NULL); | |
while (*st && f(*st)) | |
++st; | |
return st; | |
} | |
int is_word_char(char c) | |
{ | |
return isalnum(c); | |
} | |
int is_not_word_char(char c) | |
{ | |
return !is_word_char(c); | |
} | |
#define skip_punctuation(a) (skip(a, is_not_word_char)) | |
#define skip_word(a) (skip(a, is_word_char)) | |
char *find_n_word(char *sentence, int n) | |
{ | |
assert(sentence != NULL); | |
assert(n >= 0); | |
char *begin = skip_punctuation(sentence); | |
for ( ; n > 0 && *begin != 0; n--) { | |
assert(is_word_char(*begin)); | |
begin = skip_word(begin); | |
begin = skip_punctuation(begin); | |
} | |
return *begin ? begin : NULL; | |
} | |
// removes the first word in sentence | |
// and returns it | |
char *remove_word(char *sentence) | |
{ | |
assert(sentence != NULL); | |
if (*sentence == 0) | |
return NULL; | |
char *begin = sentence; | |
// at this point there is at least one alpha | |
assert(is_word_char(*begin)); | |
char *end = skip_word(sentence+1); | |
assert(end > begin); | |
char *word = strndup(begin, end - begin); | |
assert(word != NULL); | |
//shift memory, to the end | |
memmove(begin, end, strlen(end)+1); | |
return word; | |
} | |
int main(int iargs, char* args[]) | |
{ | |
// read sentence from first parameter, number to remove from second | |
if (iargs != 3) { | |
fprintf(stderr, "Error: illegal number of parameters [%d]\n\nUsage: %s <sentence> <index-base 0>\n", iargs, args[0]); | |
exit(1); | |
} | |
char *original = args[1]; | |
char *sentence = strdup(original); | |
assert(sentence != NULL); | |
int n = atoi(args[2]); | |
if (n < 0) { | |
fprintf(stderr, "Error: number of word should be a positive number [%d]\n\nUsage: %s <sentence> <index-base 0>\n", n, args[0]); | |
exit(1); | |
} | |
char *index = find_n_word(sentence, n); | |
if (index == NULL) { | |
printf("Sentence %s does not contain a word at position %d\n", sentence, n); | |
exit(1); | |
} | |
char *word = remove_word(index); | |
printf("Original sentence %s\nWithout %d word [%s]\nword [%s]\n", original, n, sentence, word); | |
sentence = realloc(sentence, strlen(sentence)+1); | |
assert(sentence != NULL); | |
free(word); | |
free(sentence); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment