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

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)
Share:
122,213
Josh Morrison
Author by

Josh Morrison

Updated on July 05, 2022

Comments

  • Josh Morrison
    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.