Link to home
Start Free TrialLog in
Avatar of paulca
paulca

asked on

Finding a Replacing a string in Visual C++

I have a string equal to:
http://localhost/....

I want to replace the first 16 characters with http://ipAddress

I have the second string set up to replace the 1st 16 characters of the first string.  

I was trying to use strncpy(1st str, 2nd str, 16) but the 2nd string was greater than 16 characters and it overlapped overlapped the 1st string.  Can anyone give me a solution to this frustrating problem.  Thanks.
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

To replace a section with a sectiopn of the same length:

char S[] = "123DEF";
char R[] = "ABC";

memcpy(S,R,3);

S now is "ABCDEF".  Note you can't uses strcpy() or strncpy() etc for this because they would place a NUL terminator character in the string.  i.e. if you did

strcpy(S,R);

S woudl be "ABC/0EF"  where the /0 is the a NUL character that marks the end of the string. i.e the string woudl be only "ABC".

continues
To replace with a different size section (either longer or shorter)

char S[10] = "12EFG";
char R[] = "ABCD";
char Buf[10];

strcpy(Buf,R); // Get start of string.
strcat(Buf,S+2); // Get new end of string.
strcpy(S,Buf); // Copy newly formed string over the original string.

S is now "ABCDEFG" Note that in this case, I had to specify a size for the original stirng (S) because that string was goign to get longer, so I had to make sure that S would have enough room for the longer string.  You have to be very careful about this when performing any operation that lengthens a string.

It is also possible to do this without using a 2nd buffer.  you can use memmove() to move the 2nd part of the string forward or backward in the array to its desired position, then use memcpy() to copy in the initial larger/smaller string.  but I thing the 1st method might be a little easier for you.

Using these NUL-terminated C-style strings is somewhat discouraged.  They are difficult to use and it is easy to make mistakes that corrupt memory, and these mistakes may be very hard to find.  I woudl recommend that you switch to using a C++ string class.  It is much easier to use and much much safer.

Let me know if you have any questions.