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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With