How to Get Substring in C
This article will introduce multiple methods about how to get substring in C.
Use the strncpy
Function to Get Substring in C
strncpy
is part of the C string library function defined in the <string.h>
header file. It copies the given number of bytes from the source string to the destination. strncpy
takes three parameters - destination char*
, source pointer, and the integer to denote the number of bytes to copy. If the number of bytes specified is more than the source string contains, then additional null bytes are stored at the destination.
The strncpy
function returns the pointer to the destination string; thus, we can chain the call into the printf
statement to directly print the substring. The following example demonstrates how to print the first four character substring and then the next 10 character substring.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *tmp = "This string literal is arbitrary";
int main(int argc, char *argv[]) {
char *str = malloc(strlen(tmp));
printf("%s\n", strncpy(str, tmp, 4));
printf("%s\n", strncpy(str, tmp + 5, 10));
free(str) exit(EXIT_SUCCESS);
}
Output:
This
string lit
Use Custom Function to Get Substring in C
Alternatively, we can define a custom function wrapper for strncpy
and specify a new interface of four parameters. Namely, the function getSubstring
will take destination and source strings plus two integers specifying the starting and end positions of the characters needed as a substring.
Note that this function prototype does not implement additional error checking, but it directly returns the char*
pointer passed on from the strncpy
call.
Similar to the previous example, getSubstring
can also be chained into the printf
function as an argument. One caveat regarding the strncpy
is that the destination and source strings must not overlap in the memory. Also, the destination pointer should point to a large enough buffer to store the source string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *tmp = "This string literal is arbitrary";
char *getSubstring(char *dst, const char *src, size_t start, size_t end) {
return strncpy(dst, src + start, end);
}
int main(int argc, char *argv[]) {
char *str = malloc(strlen(tmp));
printf("%s\n", getSubstring(str, tmp, 0, 4));
printf("%s\n", getSubstring(str, tmp, 5, 10));
free(str);
exit(EXIT_SUCCESS);
}
Output:
This
string lit
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook