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.
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.
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.
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
dest
is large enough.endIndex
is greater than beginIndex
beginIndex
is less than strlen(src)
endIndex
is less than strlen(src)
Just use memcpy.
If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.
strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.