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.
We can use string function strncpy() to copy part strings. Part of the second string is added to the first string. strcpy(destination_string, source_string, n);
Just add your offset to the str1 argument of the strncpy call. For example: strncpy(str2, str1 + 1, 5); will copy five bytes into str2 from str1 starting at index 1.
Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);
C strcpy() The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string.
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)
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.
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