Search code examples
cstringmemcpy

Remove characters from string in C


I'm having an issue removing characters from a string. I have been able to identify the characters to remove and store them as a new string but I would like a code that enables me to remove the new string's characters from the original string (where I've labelled as xxxxxxxx).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char input[120], to_del[120], new_input[120];
int a,b;


void removeString();

int main(void)
{
    printf("\nEnter your sentence: ");
    gets(input);

    printf("\nWhere to start: ");
    scanf("%d",&a);
    printf("\nHow many characters to delete: ");
    scanf("%d",&b);

    removeString();

    printf("\nNew sentence: %s\n",new_input);

    return ;
}

void removeString()
{
    memcpy(to_del, &input[a-1], b);
    new_input [strlen(input)-b] =xxxxxxxx;
    return ;
}

Solution

  • EDIT in response to @SouravGhosh comment, about overlapping strings. First I copy the string to new_input and then copy the right hand part back to input to overwrite the section which must be removed.

    int len = strlen(input);
    strcpy(new_input, input);
    if (a < len && a+b <= len)
        strcpy (input + a, new_input + a + b);
    

    I notice the rest of your code doesn't check anything is happening correctly, such as the return value from scanf, and please note gets is dangerous: it is better to use fgets with stdin.

    The strcpy instruction copies the right-hand part of the string over the part you want removed. It works by using pointer arithmetic. Adding a to input is the same as getting the address of input[a], the place where you want the removal to begin. Similary new_input[a+b] is the start of the right hand part you wish to keep.

    The point of the if condition, is that if a isn't within the string, or if the part you want removed overflows the end of the string, it can't be done.