John Smith John Smith - 16 days ago 5
C Question

Inserting string (character by character) into a larger string

I am trying to insert a string by replacing a substring in the (original) string with a new string (toInsert). The start parameter is the starting position of the substring I want to replace. Note: This is part of a larger program but I am just trying to get this function to work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROW 5
#define COLUMN 81

void insertString(char original[], int start, int length, char toInsert[]){

char buffer[COLUMN];
int i = 0;

for (i=0; i<strlen(original); ++i){
if (i>=start){
buffer[i] = toInsert[i];
}
else{
buffer[i] = original[i];
}
}

buffer[strlen(buffer)-1] = '\0';



printf("%s\n", buffer);



return;
}

int main()
{
char rep[COLUMN] = "very";
char sub[COLUMN] = "are";

char buf[ROW][COLUMN] = {
{"How are you doing"}


};
int len = strlen(sub);
int start = 4;

insertString(buf[0], start, len, rep);



return 0;
}


The problem is it only prints "How".

I want it to print "How very you doing"

Also, I have tried using strcpy but that just gives errors/warnings (something to do with pointers and I don't want to deal with pointers because I have not learned about them yet.)

Answer

Your function does not make great sense because it neither enlarge or shrink the original string though it has to do this.

And moreover it has undefined behavior due to this if statement because when i is equal to or greater than start you can access the memory beyond the string toInsert using the index i.

if (i>=start){
    buffer[i] = toInsert[i];
}

It is simpler to write the function using standard C functions.

Here you are

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

char * replaceString( char *s1, size_t pos, size_t n, const char *s2 )
{
    size_t n1 = strlen( s1 );

    if ( pos < n1 )
    {
        size_t n2 = strlen( s2 );

        if ( n != n2 )
        {

            memmove( s1 + pos + n2, s1 + pos + n, n1 - pos - n + 1 );
        }

        memcpy( s1 + pos, s2, n2 );
    }

    return s1;
}


int main(void) 
{
    {
        char s1[100] = "ab1111cd";
        const char *s2 = "22";

        puts( replaceString( s1, 2, 4 , s2 ) );
    }

    {
        char s1[100] = "ab11cd";
        const char *s2 = "2222";

        puts( replaceString( s1, 2, 2 , s2 ) );
    }

    {
        char s1[100] = "ab11cd";
        const char *s2 = "22";

        puts( replaceString( s1, 2, 2 , s2 ) );
    }

    return 0;
}

The program output is

ab22cd
ab2222cd
ab22cd

If to insert this code block

{
    char s1[100] = "How are you doing";
    const char *s2 = "very";

    puts( replaceString( s1, 4, 3 , s2 ) );
}

in the demonstrative program you will get the output

How very you doing
Comments