I'm tired of playing with this. I did this both ways I figured out how to do this, and I still cannot figure out how to get some crap char out of the substring, or its a \n or something that is putting in a end line between the substring and main string.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_LEN 256
int main(void)
{
char string1[MAX_LEN]; // main string
char string2[MAX_LEN]; // sub string
char string3[MAX_LEN]; // holding string
int position=0,i=0;
int ss=0;
int x,tsz,op;
int srt1_len, srt2_len;
printf("Enter First String: ");
fgets(string1, MAX_LEN, stdin);
printf("Enter Second String: ");
fgets(string2, MAX_LEN, stdin);
printf("Enter the insert position: ");
scanf("%d",&position);
srt1_len = strlen(string1);
srt2_len = strlen(string2);
//printf("stLen 1 %d : stLen 2 %d\n", srt1_len, srt2_len);
i=0;
// Copying the first string into another array
while(i <= srt1_len)
{
string3[i]=string1[i];
// printf("string3[i %c], string1[i %c]\n", string3[i], string1[i]);
i++;
}
tsz = srt2_len+srt1_len;
op = position+srt2_len;
if (string2[srt2_len ] == '\n')
string2[srt2_len ] = '\0';
printf("Start position %d\nsrt2_len %d", position ,srt2_len);
printf("Start op %d\n", op);
// Adding the sub-string
for(i=position;i < op;i++)
{ printf(" i = %d tsz %d\n", i, tsz);
// x = string3[i];
// printf("x = %c\n i %d\n", x, i);
// printf("top of if\n");
if(ss < srt2_len)
{ printf("ss at start of loop %d\n\n", ss);
if (string2[ss - 1] == '\n')
string2[ss - 1] = '\0';
string1[i] = string2[ss];
printf("i %d string1[i %c] = ss %d string2[ss %c]\n",i , string1[i], ss, string2[ss]);
ss += 1;
}
printf("outside bottom of if op %d \n", op);
printf("outside bottom of if tsz %d \n", tsz);
// string1[op]=x;
// if (string1[op - 1 ] == '\n')
// string1[op - 1 ] = '\0';
// output start point to length of = letter from
// copied main string holding char[size] array
// putting back what is left of string one at
// end of substring over write
// printf("string1[op %c ] = x %c\n", string1[op], x);
// printf("string1 %s\n", string1);
// op += 1;
// printf("op = %d\n",op);
}
for ( int j = i; j < tsz; j++)
{
string1[j] = string3[position];
position++;
}
printf("%s", string1);
return 0;
}
results,
Code:
// input
$ ./insert_string_3
Enter First String: MAIN STRING
Enter Second String: substring
Enter the insert position: 5
// output
MAIN substring
STRING
if you do run this, comment out the third loop, then uncommnent that code inside of the second loop and what printf you want to see what is going on. towards the end of the run you're going to start seeing. stuff like this
Code:
x =
i 21
top of if
outside bottom of if op 31
outside bottom of if tsz 22
string1[op ] = x
but with them little squares in the output that have them four really little number or whateer they are in them.
oh yeah and comment this out too
Code:
if (string2[srt2_len ] == '\n') string2[srt2_len ] = '\0';
it's up top