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.
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
needs a length, strncpy(dest, &c[20], 8)
. Whether dest is a char*
pointing to a sufficiently large malloc
ed memory area or a sufficiently large char[N]
doesn't matter. –
Alethaalethea d
? strcpy(d, &c[20])
copies the part of c
from position 20 to the 0-terminator (inclusive) into the array d
. –
Alethaalethea 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.
do I do this
not do I d
. ideone.com/u8HRuI –
Septet Sounds like you are looking for the strncpy function. Don't mind the C++ site, the documentation is for C.
Or you can also use the strcpy
function.
Use memcpy which may be a better fit, can only copy a portion of a string.
Using strncpy or strcpy actually copies a whole string up to the '\0' terminator.
In any case, it is prudent and wise, to assume there is plenty of space for the resulting string otherwise buffer overflows so ensure there is sufficient space in the buffer.
© 2022 - 2024 — McMap. All rights reserved.