c - Inserting string (character by character) into a larger string -
i trying insert string replacing substring in (original) string new string (toinsert). start parameter starting position of substring want replace. note: part of larger program trying function 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 = 0; (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 doing"} }; int len = strlen(sub); int start = 4; insertstring(buf[0], start, len, rep); return 0; }
the problem prints "how".
i want print "how doing"
also, have tried using strcpy gives errors/warnings (something pointers , don't want deal pointers because have not learned them yet.)
your function not make great sense because neither enlarge or shrink original string though has this.
and has undefined behavior due if statement because when i
equal or greater start
can access memory beyond string toinsert
using index i
.
if (i>=start){ buffer[i] = toinsert[i]; }
it simpler write function using standard c functions.
here 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 insert code block
{ char s1[100] = "how doing"; const char *s2 = "very"; puts( replacestring( s1, 4, 3 , s2 ) ); }
in demonstrative program output
how doing
Comments
Post a Comment