How to How to remove the two middle characters from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void remove_two_middle_characters_from_string(char s[]) {
    int size = strlen(s);
    int mid = (size / 2) - 1;

    char tmp[256] = "";

    // char * strncpy ( char * destination, const char * source, size_t num );

    strncpy(tmp, s, mid);
    strncpy(tmp + mid, s + mid + 2, size - mid - 1);

    tmp[size - 1] = '\0';

    strcpy(s, tmp);
}

int main() {
    char s1[] = "abcde";
    remove_two_middle_characters_from_string(s1);
    printf("%s\n", s1);

    char s2[] = "abcdef";
    remove_two_middle_characters_from_string(s2);
    printf("%s\n", s2);

    return 0;
}




/*
run:

ade
abef

*/

 



answered Jun 12, 2024 by avibootz

Related questions

1 answer 107 views
2 answers 114 views
1 answer 132 views
1 answer 116 views
1 answer 98 views
...