Skip to content

Instantly share code, notes, and snippets.

@derekli66
Last active September 6, 2015 13:57
Show Gist options
  • Save derekli66/32d267cdd5ff61b25362 to your computer and use it in GitHub Desktop.
Save derekli66/32d267cdd5ff61b25362 to your computer and use it in GitHub Desktop.
Programming exercise 6-3 in chapter 6 of Pointers on C.
#include <stdio.h>
#include <stdlib.h>
#include <String.h>
/*
* === FUNCTION ======================================================================
* Name: del_str
* Description: Delete substring in the source string
* =====================================================================================
*/
int
del_str (char str[], char const *substr )
{
int index_start = 0;
int index_end = 0;
char *iterator;
// Find index of first char
for (iterator = str; *iterator != *substr; iterator++) {
index_start++;
}
for (index_end = index_start; *substr != '\0'; substr++) {
if (*iterator++ != *substr) {
break;
}
index_end++;
}
if (*substr != '\0') return 0;
int length = strlen(str);
// Add characters from index_end to the start position of substr
for (int i = index_end; i < length; i++) {
str[index_start++] = *(str + index_end++);
}
str[index_start] = '\0';
// Match rest of characters
return 1;
} /* ----- end of function del_str ----- */
/*
* === FUNCTION ======================================================================
* Name: main
* Description:
* =====================================================================================
*/
int
main ( int argc, char *argv[] )
{
char string1[] = "ABCDEF GXYZ";
char *sub_str = "DEF";
int final = del_str(string1, sub_str);
printf("Result: %d\nFinal String: %s\n", final, string1);
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment