/*write a program to insert a string into main string*/
#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i = 0, j = 0, k = 0, pos;
printf("enter main text: ");
gets(text);
printf("enter string to be inserted: ");
gets(str);
printf("enter the position to be inserted: ");
scanf("%d", &pos);
while (text[i] != '\0')
{
if (i == pos)
{
while (str[k] != '\0')
{
ins_text[j] = str[k];
j++;
k++;
}
}
else
{
ins_text[j] = text[i];
j++;
}
i++;
}
ins_text[j] = '\0';
printf("\n the new string is: ");
puts(ins_text);
return 0;
}
In the terminal
$ ./a.exe
enter main text: newsman
enter string to be inserted: paper
enter the position to be inserted: 4
The new string is: `newspaperan`
In final output above :- "the new string is : newspaperan" the letter "m" is missing.
I think it is due to post incrementing "j++" in while loop;
any way to fix it?
>Solution :
That is the else that causes your problem. When you inserted the word in the middle you must continue as usual just after.
while (text[i] != '\0') {
if (i == pos) { // insert the word
while (str[k] != '\0') {
ins_text[j++] = str[k++];
}
}
ins_text[j++] = text[i++];
}