QUESTION 38 · String Operations
Write a C function to extract a substring from a given position.
5 marksAnswer in brief
A substring is a consecutive part of a string. This example uses a zero-based start index and a requested character count.
Algorithm
- Find the source length.
- Reject start > length or count > length - start.
- Reject a destination capacity of zero or count >= capacity.
- Copy count characters beginning at start, then write the null terminator.
Worked example
For source "Programming", start 3 selects the first g. Taking count 4 copies g, r, a and m, producing "gram". The extracted text must receive its own terminator; it cannot depend on the next source character being null.
Boundary cases
start equal to the source length is valid only when count is zero. The result is an empty string. A request extending beyond the end is rejected. Testing count against length - start after validating start avoids adding start + count unnecessarily.
Storage rule
The sample uses a separate output array, so source and destination do not overlap. An interface should state its capacity and bounds clearly. C does not provide a special substring assignment operator that automatically allocates and terminates a result.
Complexity
The strlen pass takes O(n) for source length n. Copying k requested characters takes O(k), so the complete function is O(n + k), which is O(n) for a valid k <= n. Output storage needs O(k + 1) positions, while counters add O(1) auxiliary space. A function receiving a known validated source length could avoid scanning it again.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int substring(const char *s, size_t start, size_t count, char out[], size_t capacity)
{
size_t length = strlen(s);
if (start > length || count > length - start || capacity == 0 || count >= capacity) { return 0; }
for (size_t i = 0; i < count; ++i) { out[i] = s[start + i]; }
out[count] = '\0';
return 1;
}
int main(void)
{
char result[20];
if (!substring("Programming", 3, 4, result, sizeof result)) { puts("Invalid request"); return 1; }
puts(result);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
gram