[c] 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.

This question is related to c string substring

The answer is


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.


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.


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)

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to substring

Go test string contains substring How does String substring work in Swift Delete the last two characters of the String Split String by delimiter position using oracle SQL How do I check if a string contains another string in Swift? Python: Find a substring in a string and returning the index of the substring bash, extract string before a colon SQL SELECT everything after a certain character Finding second occurrence of a substring in a string in Java Select query to remove non-numeric characters