Substring In C Tutorial

Substring is an operation where some part of the given string is extracted. Most of the popular and recent programming languages provide a function for substring operations. C Programming language provides different methods and functions in order to implement substring operations.

What Is a Substring Operation?

Substring is used to return some parts of the given string accord to the specified parameters. For example, we can search the “Tut” term int the string “” which will return the “Tut” if we substring. Alternatively, we can specify the start and length parameters in order to return the substring. The index starts from 0 and we will specify 4 as the start index. The length will be 3 because there are 3 characters in the “Tut”.

Actually there are two ways to return substring. The first one is the strstr() the function which is used to find a string in the given string. It is like searching the first occurrence of a needle in the haystack. The second method is to create our own substring in the C programming language.

Substring with strstr() Function

strstr() function is provided with the string.h library. It only accepts two parameters where the first parameter is the string we want to search in and second is the term we want to search in the first string. The syntax of the strstr() function is like below.

char *strstr(const char *haystack, const char *needle);
  • const char *haystack is the complete string we want to search in. The type is char pointer which is an equivalent string in C.
  • const char *needle is the search term that will be searched in the haystack. the needle is char pointer which is a string.
  • char *strstr(…) is the function name and the return type which will return the first occurrence pointer of the needle.

We will make an example for the C strstr() function in order to get the substring start. We will prov

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

int main () {
   const char haystack[20] = "";
   const char needle[10] = "Tut";
   char *ret;

   ret = strstr(haystack, needle);

   printf("The substring start is: %s\n", ret);

Leave a Comment