Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

#1
October 30th, 2012, 02:03 PM
 Jan4185
Registered User

Join Date: Oct 2012
Posts: 7
Time spent in forums: 2 h 57 m 24 sec
Reputation Power: 0

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

#2
October 30th, 2012, 02:12 PM
 bdb
Contributing User

Join Date: Aug 2012
Posts: 156
Time spent in forums: 1 Week 15 h 48 m 11 sec
Reputation Power: 32
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.

#3
October 30th, 2012, 02:16 PM
 salem
Contributed User

Join Date: Jun 2005
Posts: 3,839
Time spent in forums: 2 Months 3 Weeks 2 Days 19 h 1 m 4 sec
Reputation Power: 1774
Consider that the string will always be split into 3 logical components
<pre><replace><post>
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

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Help please *Strings*