Open In App

Get a Substring in C

Last Updated : 06 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A substring is a contiguous sequence of characters within a string. In this article, we will learn how to extract a substring using a C program.

The simplest method to get a substring from a larger string is by using strncpy() function. Let’s take a look at an example:

C++
#include <stdio.h>
#include <string.h>

int main() {
    char s[] = "Hello, Geeks!";
  	int pos = 7, l = 5;
  
    // Char array to store the substring
    char ss[20];

    // Extract substring of length 5 and from index 7
  	// using strncpy
    strncpy(ss, s + 7, 5);

  	// Null terminate the substring
    ss[5] = '\0';

    printf("%s", ss);
    return 0;
}

Output
Geeks

Explanation: The strncpy() function copies a fixed number of characters from the source string to the destination substring array but we have to manually add a null terminator to the result.

There are also a few other methods to extract the substring of specified length from the given position in a larger string in C. Some of them are as follows:

Manually Using Loop

Iterate the string from the given position using a loop and copy the specified number of characters from this position to the substring.

C
#include <stdio.h>

void getSub(char *s, char *ss, int pos, int l) {
    int i = 0;

    // Copy substring into ss
    while (i < l) {
        ss[i] = s[pos + i];
        i++;
    }
    
    // Null terminate the substring
    ss[i] = '\0';  
}


int main() {
    char s[] = "Hello, Geeks!";
  
    // Char array to store the substring
    char ss[20];  

    // Extract substring starting from 
    // index 7 with length 5 ("Geeks")
    getSub(s, ss, 7, 5);

    printf("%s", ss);
    return 0;
}

Output
Geeks

Using Pointers

The above algorithm can also be applied using pointers. Move the pointer to point to the starting position of the substring and copy the specified characters.

C
#include <stdio.h>

void getSub(char *s, char *ss, int pos, int l) {
    int i = 0;
    
    // Move pointer to the pos
    s += pos;
  
    // Copy substring of lenght l
    while (l--) *ss++ = *s++;
    
    // Null terminate the string
    *ss = '\0'; 
}

int main() {
    char s[] = "Hello, Geeks!";
  	int pos = 7, l = 5;
  
    // Char array to store the substring
    char ss[20];  

    // Extract substring starting from 
    // index 7 with length 5 ("Geeks")
    getSub(s, ss, 7, 5);

    printf("%s", ss);
    return 0;
}

Output
Geeks

Next Article

Similar Reads