Insert word at a location in a string
C program to insert word at any desired location in a string.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
int split_words(char str[MAX], char words[MAX][MAX])
{
int i, j, count;
char prev_char;
i = 0;
j = 0;
count = 0;
prev_char = '\0';
while(1)
{
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\0')
{
if(prev_char!=' ' && prev_char!='\t' && prev_char!='\0')
{
words[count][j] = '\0';
count++;
j = 0;
}
}
else
{
words[count][j] = str[i];
j++;
}
prev_char = str[i];
if(str[i] == '\0')
break;
else
i++;
}
return(count);
}
void main()
{
char str1[MAX], str2[MAX];
char words[MAX][MAX];
int count, i, j;
int pos, new_pos, len1, len2;
printf("Enter the string\t:");
gets(str1);
printf("Enter the word to be added to the string\t:");
gets(str2);
printf("Enter the position at which word is to be added\t:");
scanf("%d",&pos);
count = split_words(str1, words);
if(pos<=0 || pos>count)
{
printf("\nInvalid position");
getch();
exit(0);
}
new_pos = 0;
for(i=0;i<pos-1;i++)
{
new_pos = strlen(words[i]) + new_pos;
}
new_pos = new_pos + (pos-1); //blank spaces
len1 = strlen(str1);
len2 = strlen(str2);
str2[len2] = ' ';
str2[len2+1] = '\0';
len2 = strlen(str2);
for(i=len1-1;i>=new_pos-1;i--)
{
str1[i+len2] = str1[i];
}
for(i=0;i<len2;i++)
{
str1[new_pos+i] = str2[i];
}
str1[len1+len2] = '\0';
printf("\nModified string\t:%s",str1);
getch();
}
Output
Enter the string :welcome to coursecrux.com, coding!!!
Enter the word to be added to the string :happy
Enter the position at which word is to be added :4
Modified string :welcome to coursecrux.com, happy coding!!!