1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Rep Power

    Help please *Strings*

    Hello there, hope you could help me out with my question about strings.

    So my question is..
    I have 3 strings , I need to find the second string in the first one(search one string in another string) and then to replace it with the third string.

    For ex':
    a = abcde
    b = cd
    c = xx
    The result need to be: a = abxxe

    Tnx for help :) :hi:
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Rep Power
    Assuming length of b and c are the same, use strstr() and strncpy().
    If the length are different, you need to "complicate" the strncpy(), by using a user-defined function (or code) instead :)
    Last edited by bdb; October 30th, 2012 at 02:20 PM.
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    Consider that the string will always be split into 3 logical components
    Both <pre> and/or <post> can be empty strings.

    Now, if you do
    x = strstr(a,b);

    Then using pointer arithmetic
    x - a
    gives you the length of <pre>

    x + strlen(b)

    gives you the start of <post>

    Once you know these things, the rest is just carefully chosen strcpy or strncpy calls to assemble the new string.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo