user6005857 user6005857 - 2 months ago 8
C Question

How to write a C function that removes a portion of a string?

I want to write a C function that removes a portion of a string for a given index range.

For example, if the input string is "ABCDEFGHIJK" and the start index is 2 and the end index is 5 then the output should be: "ABGHIJK".

I am attempting to do this using two functions, one function that gets the substring we want to delete:

void get_substring(char string[], char substring[], int start, int end) {
strncpy(substring, string + start, end - start + 1);
}


and then a second function that deletes this substring:

void remove_portion(char string[], char substring[]) {
// memmove?
}


Another possibility I was thinking about is to directly modify the original string without using a substring:

void remove_portion(char string[], int start, int end) {
// if end is less then the length of the string, then
// copy everything after string[end] into a temp string
// Then replace string[start] with '\0' and then concatenate
// string and temp.
// If end is greater than the length of string then just replace
// string[start] with '\0'.
}


Is this the correct approach? Are there any built in functions from string.h that can be useful here?

Answer

I would go with using memmove as in the 2nd approach:

void remove_portion(char string[], int start, int end) 
{
    if (start>=0 && end>=start && start<strlen(string) && end<strlen(string)) {  // some more sanity checking (EDIT added later)
         memmove(string+start, string+end+1, strlen(string)-(end+1)+1);  // final +1 to copy string terminator
    }
}

Also note that in your first example (with strncpy) is not going to to copy the ending string terminator \0 to substring. So you'll need to add

substring[end - start + 1]= '\0'; 

to that.