How to Get a Substring in C

  1. memcpy() Function to Get a Substring in C
  2. strncpy() Function to Get a Substring in C

This tutorial introduces how to get a substring from the character value in C. There are different methods for getting a substring from the character like memcpy() and strncpy().

memcpy() Function to Get a Substring in C

The memcpy() function copies the number of characters from the source to the destination’s memory area. This function is available in the <string.h> header file.

This function creates a problem when the addresses of source and destination overlap. This function doesn’t check for a null address or whether the overflow occurs or not.

The memcpy() function returns a pointer to the destination string. There is no return value to display an error.

Syntax of memcpy()

void *memcpy(void *destination_string, const void *source_string, size_t number);
  • The destination_string is a pointer to the destination string.
  • The source_string is a pointer to an array of original character type of value.
  • The number is the number of characters.
#include <stdio.h>
#include <string.h> 

int main(void)
{
    char *text = "The test string is here";
    char subtext[7];

    memcpy(subtext,&text[9],6);
    subtext[6] = '\0';
    printf("The original string is: %s\n",text);
    printf("Substring is: %s",subtext);

    return 0;
}

Output:

The original string is: The test string is here
Substring is: string

strncpy() Function to Get a Substring in C

The strncpy() function is the same as strcpy() function. The only difference is that the strncpy() function copies the given number of characters from the source string to the destination string. The strncpy() function is available in the<string.h> header file.

This function returns a pointer to the destination string after copying the source string.

Syntax of strncpy()

void *strncpy(void *destination_string, const void * source_string, size_t number);
  • The destination_string is a pointer to the destination string.
  • The source_string is a pointer to an array of original char values.
  • The number is the number of characters.

If the strncpy() function encounters a null character in the source_string, the function will add null characters to the destination_string.

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

int main(void)
{
    char *text = "The test string is here";
    char subtext[7];

    strncpy(subtext,&text[9],6);
    subtext[6] = '\0';
    printf("The original string is: %s\n",text);
    printf("Substring is: %s",subtext);

    return 0;
}

Output:

The original string is: The test string is here
Substring is: string

Related Article - C Char

  • How to Convert Integer to Char in C
  • Related Article - C String

  • How to Convert a String to Integer in C