Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a starting and ending indices, how can I copy part of a string in C?

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.

like image 438
Josh Morrison Avatar asked Jun 01 '11 17:06

Josh Morrison


People also ask

How can I copy just a portion of a string in C?

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);

How do I copy part of a string to another?

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.

How do you get a certain index of a string in C?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);

Which function is used to copy the string in C?

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.


2 Answers

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)
like image 171
Binary Worrier Avatar answered Sep 16 '22 15:09

Binary Worrier


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.

like image 24
karlphillip Avatar answered Sep 19 '22 15:09

karlphillip