Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy end of string in C

I am trying to use strncpy to only copy part of a string to another string in C.

Such as:

c[] = "How the heck do I do this";

Then copy "do this" to the other string, such that:

d[] = "do this"

Help is appreciated.

like image 798
Church Avatar asked Sep 20 '12 00:09

Church


2 Answers

Just pass the address of the first letter you want to copy: strcpy(dest, &c[13]).

If you want to end before the string ends, use strncpy or, better, memcpy (don't forget to 0-terminate the copied string).

like image 182
Daniel Fischer Avatar answered Sep 19 '22 14:09

Daniel Fischer


strncpy is (essentially always) the wrong choice. In this specific case, it'll work, but only pretty much by accident -- since you're copying the end of a string, it'll work just like strcpy. That of course, leads to the fact that strcpy will work too, but more easily.

If you want to handle a more general case, there's a rather surprising (but highly effective) choice: sprintf can do exactly what you want:

sprintf(d, "%s", c+20);

sprintf (unlike strncpy or strcpy) also works for the most general case -- let's assume you wanted to copy just do I to d, but have d come out as a properly NUL-terminated string:

sprintf(d, "%*s", 4, c+13);

Here, the 4 is the length of the section to copy, and c+13 is a pointer to the beginning of the part to copy.

like image 38
Jerry Coffin Avatar answered Sep 21 '22 14:09

Jerry Coffin