473,925 Members | 16,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const char *Str_Replace(co nst char *c, const char *sub, const char *s3)

7 New Member
Hello, I need some help..

I have to replace in s1, the string s2 with the string s3. I first found if s2 was a substring in s1, but i dont know what to do from here, I'm lost..

example: s1 = "It is a good day to die", s2 = "die", s3 = "pay up"
=> after execution s1 will be "it is a good day to pay up"

Here's the code for the function:

Expand|Select|Wrap|Line Numbers
  1. const char *String_Replace(const char *c, const char *sub, const char *s3)
  2. {
  3.       if(!*sub)
  4.           return c;
  5.       for (;*c;c++)
  6.       {
  7.           if(*c==*sub)
  8.           {
  9.                const char *h,*n;
  10.                for(h=c,n=sub;*h&&*n;h++,n++)
  11.                {            
  12.                     if(*h!=*n)
  13.                          break;
  14.                }
  15.                if(!*n)
  16.                     return c;                   
  17.           }
  18.       }
  19.       return 0;
  20. }
please help, I'm lacking ideas..
Thanks
Nov 10 '09 #1
10 4919
donbock
2,426 Recognized Expert Top Contributor
You need to create the output string -- you can't merely alter input string s1. Why do I say that? The first reason is that the s1 parameter is declared as a const char *, which means that the content of the string can't be changed. The second reason is that the output string can be longer than the input string -- you can't count on the memory allocation for s1 to be big enough to hold the longer string.

Do you need to replace the first occurrence of s2 or all occurrences? If you only need to replace the first occurrence then you can quickly determine how much memory to allocate for the output string: strlen(s1) + strlen(s3) + 1. This is actually a little more memory than you need, but I wouldn't worry about it.

By the way, your code is not consistent with your text. Are the function arguments s1, s2, s3 or are they c, sub, s3?
Nov 10 '09 #2
LuxOcculta
7 New Member
the arguments are c, sub, and s3, and i have to change for every occurrance.. and i must not use string.h functions :|
Nov 10 '09 #3
donbock
2,426 Recognized Expert Top Contributor
OK ... I assume that c is the same as s1, and sub is the same as s2.

Don't worry about <string.h> ... it is trivial to roll your own version of strlen, as long as you give it a different name.

What's the answer to the question whether you are supposed to replace all instances of sub/s2 or only the first?
Nov 10 '09 #4
LuxOcculta
7 New Member
replace for all instances.. is the function helping in any way ?
Nov 10 '09 #5
donbock
2,426 Recognized Expert Top Contributor
Copy from s1 to the output string until you find an instance of s2.
Then copy all of s3 into the output string.
Then resume copying from s1 after the end of the embedded instance of s2.
Repeat these steps until you reach the end of s1.

You need to be careful that you don't write past the end of the output string allocation. You can do this either by allocating a big enough output string or by increasing the allocation as needed.

Next question about the requirements: does this function need to support recursive replacements? That is, if new instances of s2 are constructed by pasting in s3 then do those new instances also need to be replaced? If so, then how do you protect yourself from infinite loop when s3 itself contains an instance of s2?
Nov 10 '09 #6
LuxOcculta
7 New Member
no, it didnt say anything about recursive replacement..
Nov 10 '09 #7
LuxOcculta
7 New Member
offtopic: Do you know any books/tutorials to help me understand better:
(expr) ? val1 : val2 ;
are there more of these ?
Nov 11 '09 #8
Markus
6,050 Recognized Expert Expert
@LuxOcculta
See the conditional / ternary operator.
Nov 11 '09 #9
LuxOcculta
7 New Member
i did this so far... but it isnt working...my brain wont work with me today...

Expand|Select|Wrap|Line Numbers
  1. char *String_Replace(char *c,char *sub,char *s3)
  2. {
  3.      char *u;
  4.      if(!*sub)
  5.          return 0;
  6.      for (;*c;c++)
  7.      {
  8.          if(*c==*sub)
  9.          {
  10.               const char *h,*n,*m;
  11.               for(h=c,n=sub;*h&&*n;h++,n++)
  12.               {            
  13.                    if(*h!=*n)
  14.                         break;
  15.               }
  16.               if(!*n)
  17.               {
  18.                      while(!*m)
  19.                      {
  20.                          *u=*m;
  21.                          cout<<*u;
  22.                          u++;
  23.                          m++;
  24.                      }                    
  25.               }                                    
  26.          }
  27.          *u=*c;
  28.          u++;
  29.      }
  30.      return u;
  31. }
Nov 15 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

7
4379
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
11
813
by: Paul Emmons | last post by:
In writing a function similar to strstr(), I'm calling both of the arguments "const char *". My compiler (gcc) complains "warning: return discards qualifiers from pointer target type" unless I have the function return "const char*" as well (rather than just "char *"). In turn, any pointer receiving this value when calling the function must also be "const char *" or the compiler will complain, "warning: assignment discards qualifiers...
8
2603
by: Roger Leigh | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 A lot of functions use const pointer arguments. If I have a non-const pointer, it is transparently made const when I pass it to the function, e.g. char * -> const char *. However, this does not appear to work when I add another level of indirection: void test1 (char **value) {}
0
1364
by: Kurt Ng | last post by:
Need help quick!!! Am really stuck on this problem! I have a C dll, and it uses a nested struct. (see below) The struct has 2 layers of nested structs. The first field in the first struct is a char*. I used StructLayout.Sequential to port each of the structs to C#, and I used UnmanagedType.LPStr to marshal the char* to C# string, but the resulting struct data are stored wrong when passed into the dll's api call. The char* is...
2
2189
by: TonyM | last post by:
Q: Is there a good way to overcome this apparent bug without modifying the mfc code? ___________________________________ Info: Although it is NOT a good idea, I seemed to have perhaps located a bug in this function with the GetLength call whose results are sent to the sub-call to Concatenate. So I added the following and it asserts on particular strings that are used. (I am not sure if this makes any difference, but I am using class...
10
14502
by: lchian | last post by:
Hi, For two stl strings s1 and s2, I got different results from strcmp(s1.c_str(), s2.c_str()) and s1.compare(s2) can someone explain what these functions do? It seems that strcmp gives the "right" (i.e.wysiwyg) answer while compare() does not.
3
11796
by: DG is a god.... | last post by:
Dear All , This is my first post - please go easy...! I have a DLL written in C++ that has the following function exported from it -: char** ListHandles(int *processID); The processID parameter is used to find all associated open file
0
1882
by: d3x0xr | last post by:
Heh, spelled out in black and white even :) Const is useles... do NOT follow the path of considering any data consatant, because in time, you will have references to it that C does not handle, and you'll be left with just noisy compiler warnings and confusion. if you start a project with all char *, and char ** and even char ***, if you begin at the low level weeding out references of 'passing const char * to char * ( such as...
0
1231
by: lavanya81 | last post by:
Hi, I am a software engg. working as developer.Right now I am working in compiler validation project. And my question is - what are the possibilities of writing C codes using the keyword 'const'.I have written some and need few more..Plz go thru and let me other ossibilities.. const int degrees = 360; /* degrees is constant */ int const degrees1 = 180; /* degrees is constant */
0
10097
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10598
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9800
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8155
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7314
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6012
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4845
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4388
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.