replace and concatenate a string

P

Puneet

Hi,

Proabably my solution is not a good solution but it can help and this
is what you want.

char *c="file.txt";
char *con="AB.txt"
char *result;

strncpy (result, c, strlen(c)-strlen(".txt"));
strcat (result, con);

puts (result);

PG.
 
M

Marc Boyer

Le 27-10-2005 said:
Hi,

Proabably my solution is not a good solution but it can help and this
is what you want.

char *c="file.txt";
char *con="AB.txt"
char *result;

And where is the variable pointed by result ?

This should produce better result:
char result[ sizeof("file.txt")-sizeof(".txt")+sizeof("AB.txt")];
strncpy (result, c, strlen(c)-strlen(".txt"));

Did you test it ? I am a bit tired, but I think that
the final '\0' is not copied.
strcat (result, con);

Why str*n*cpy in one case and strcat in the other ?
puts (result);

Marc Boyer
 
P

Puneet

Agreed,

If you are using array not pointer then as marc suggest that is the
better way of declaring size.

Now another question of marc "Why str*n*cpy in one case and strcat in
the other ? "

answer is in first strncpy i am copying the string file in result
string. So only rquired part i am copying after turncating ".txt" from
that. And after that i concat the second string in result string for
required result.

PG.
 
N

Netocrat

Thanks. Yes, both strings will always end with ".txt". Also, the string
to be inserted
will always have 2 characters before ".txt" i.e "AB". Also the first
string (Char* c) will never be only ".txt".

Then your code looks OK, except that I noticed another off-by-one error in
the final line. I'll quote your original code with existing corrections
asterisked:
char* c="file.txt";
char* con="AB.txt";
int len=strlen(c);
len++;
char* newc=new char(len+2);//since I want to add "AB" strcpy(newc,c);
* this is C++ - C would use malloc()
strcpy(&newc[len-6],con);
* off-by-one: should be [len-5]
newc[len+2]='\0';
off-by-one: should be [len+1]

[...]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top