Skip to main content

Get Substring in C

To get a substring from a C string, you can use the strncpy() function to copy a specified number of characters from the original string to a new buffer.

Here's an example function that extracts a substring from a C string:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char* substring(char* str, int start, int length) {
  	// Assume start and length are valid
  	// Then
    // Allocate memory for the new substring
    char* sub = (char*)malloc(sizeof(char) * (length + 1));

    // Copy the substring to the new buffer
    strncpy(sub, str + start, length);

    // add the null terminator to the end of the string
    sub[length] = '\0';

    return sub;

int main() {
    char str[] = "Hello, world!";
    char* sub = substring(str, 7, 5);
    printf("Substring: %s\n", sub);
    return 0;

This function takes three arguments: the original string str, the starting index of the substring start, and the length of the substring length. It returns a new dynamically allocated string that contains the extracted substring.

This program will output:

Substring: world

The memory allocated for the new string using malloc() must be freed using free() when it's no longer needed, to avoid memory leaks.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment