C program to replace the sub string with another string.

C Strings:
Write a C program to replace the sub string in a string with another string.
In this program, We replace string with another string, if the entered string is the sub string of main string, otherwise function replace_str returns the original string as it is. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <string.h>

char *replace_str(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;

if(!(p = strstr(str, orig)))
return str;

strncpy(buffer, str, p-str);
buffer[p-str] = '';

sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));

return buffer;
}

int main(void)
{
char str[100],str1[50],str2[50];
printf("Enter a one line string..n");
gets(str);
printf("Enter the sub string to be replaced..n");
gets(str1);
printf("Enter the replacing string....n");
gets(str2);
puts(replace_str(str, str1, str2));

return 0;
}
Read more Similar C Programs
Searching in C

C Strings

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

Leave a Reply