this program will replace a substring from the string with a new string . It is working perfect ...

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

 char *replace(char *st, char *orig, char *repl)
 {
	 char buff[50];
	 char *ch;
	 if ( !( ch = strstr( st, orig ) ) )
	 return st;
	 strncpy(buff, st, ch-st);
	 buff[ch-st] = 0;
	 sprintf(buff+(ch-st), "%s%s", repl, ch+strlen(orig));
	 return buff;
  }
void main()
{
  clrscr();
  char s[20],s1[30],s3[40];
  cout<< " Enter the String ";
  gets(s);
  cout<<" Enter the string to replace ";
  gets(s1);
  cout<<"Enter new string";
  gets(s3);
  puts(replace(s, s1, s3));
  getch();
}

help me to do this without using any string Library functions and in simple mode. please help me...

Recommended Answers

All 3 Replies

Well, split the problem:
subproblem 1. find substring
subproblem 2. if found, make a room (move the rest forward or back)
subproblem 3. copy new string contents to the room
Better forget the snippet presented above: it's a very very bad replace implementation (the worst I've ever seen ;) - it's the other story why)...

Next time Use code tag with the language specifier:
[code=cplusplus] source

[/code]

help me to find the solution , give me small bit of code to replace . U said it is a worst method .Then give me the best one man ..!!!!

It seems the best replace code is too sofisticated for you ;)
Make a little effort yourself, type codes instead of exclamation marks. It's not so interesting problem for me to break this forum rules (perfectly reasonable).
Regrettably (or may be fortunately), I'm not your personal programmer till now...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.