Given a starting and ending indices, how can I copy part of a string in C?
122,213
Solution 1
Have you checked strncpy?
char * strncpy ( char * destination, const char * source, size_t num );
You must realize that begin and end actually defines a num of bytes to be copied from one place to another.
Solution 2
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
- Validated that
dest
is large enough. -
endIndex
is greater thanbeginIndex
-
beginIndex
is less thanstrlen(src)
-
endIndex
is less thanstrlen(src)
Author by
Josh Morrison
Updated on July 05, 2022Comments
-
Josh Morrison almost 2 years
In C, how can I copy a string with begin and end indices, so that the string will only be partially copied (from begin index to end index)?
This would be like 'C string copy'
strcpy
, but with a begin and an end index.