40

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.

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Josh Morrison
  • 7,488
  • 25
  • 67
  • 86

3 Answers3

82

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)
Morgoth
  • 4,935
  • 8
  • 40
  • 66
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
  • 2
    To get `abc` from `"abc"`, you'd do: `strncpy(dest, src + 1, strlen(src) - 2);`. This should be the accepted answer. – gsamaras Dec 07 '18 at 09:05
25

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.

karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • 3
    As I noted in a previous answer, there is almost no reasonable question to which `strncpy` is a good answer. http://stackoverflow.com/questions/2889421/how-to-copy-a-string-into-a-char-array-in-c-without-going-over-the-buffer/2889483#2889483 – Jerry Coffin Jun 01 '11 at 17:45
13

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.