This C Program inserts character/word in any desired location in a string.
Here is source code of the C Program to insert character/word in any desired location in a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Insert Character/Word in any Desired Location
* in a String
*/
#include <stdio.h>
#include <string.h>
void main()
{
int i, j, count = 0, pos, flag = 0;
char s1[100], s2[10], s3[100];
char *ptr1, *ptr2, *ptr3;
printf("\nenter the String:");
scanf(" %[^\n]s", s1);
printf("\nenter the string to be inserted:");
scanf(" %[^\n]s", s2);
printf("\nenter the position you like to insert:");
scanf("%d", &pos);
ptr1 = s1;
ptr3 = s3;
/*COPYING THE GIVEN STRING TO NEW ARRAY AND INSERTING THE STRING IN NEW ARRAY*/
for (i = 0, j = 0;*ptr1 != '\0'; ptr1++, i++, j++, ptr3++)
{
s3[j] = s1[i];
if (*ptr1 == ' ' && flag != 1)
++count;
if (flag != 1 && count == pos - 1)
{
flag = 1;
for(ptr2 = s2;*ptr2 != '\0'; ptr2++)
{
s3[++j] = *ptr2;
ptr3++;
}
s3[++j] = ' ';
ptr3++;
}
}
s3[j] = '\0';
printf("\nthe string after modification is\n\n %s\n", s3);
}
$ cc string10.c $ a.out enter the string:Welcome to Sanfoundry's C Programming Class, Welcome Again to C Class! enter the word to insert:Sanfoundry's enter the position you like to insert:3 the string after modification is Welcome to Sanfounsry's Sanfoundry's C Programming Class, Welcome Again to C Class!
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Computer Science Books
- Buy C Books
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Apply for Computer Science Internship