C Program to Extract a Portion of String

Posted in

C Program to Extract a Portion of String
vinaykhatri

Vinay Khatri
Last updated on November 13, 2024

    Extracting a substring from a string is one of the most common operations that you may need to use in your code. In C, it is quite easy to extract a portion of a string with the intention of using it separately from the parent string.

    In this tutorial, we have written a C program that can extract a substring from a given string. However, before sharing the C program, let's take a look at the steps that the program follows to extract a substring from the string input by a user.

    Steps to Create the Program

    • Ask the user to enter a string.
    • Ask the user to enter the starting and endpoint of the string they want to extract. These points will represent the index value of the String.
    • Pass the string, starting point, and ending point as the arguments to the user-defined function sub_string().
    • The sub_string() function prints a sequence of characters that represents the substring that the user has requested.

    C Program to Extract a Portion of a String

    #include<stdio.h>
    #include <conio.h>
    #include<string.h>
    void sub_string(char *s, int start,int end)
        {
           int i;
           for(i=start; i<= end; i++)
               printf("%c",s[i]);
        }
    void main()
       {
          char str[100];
          int s,e;
          clrscr();
    
          printf("Enter a String: ");
          gets(str);
    
          printf("Enter the starting Index: ");
          scanf("%d",&s);
    
          printf("Enter the Last Index: ");
          scanf("%d",&e);
    
          if(e > strlen(str) || (s>strlen(str)))
                printf("Starting or End value of Index is out of Range");
    
          else
                sub_strin(str,s,e);
          getch();
    
      }

    Output:

    Enter a String: Welcome To TechGeekBuzz
    Enter the starting Index: 1
    Enter the Last Index: 9
    elcome To

    Note: gets(): It is an in-built C function that can take string input from the user, and it is similar to the scanf() function.

    To Sum it Up

    Extracting a substring from a string in C is quite simple. In our program above, we have written a function that accepts three arguments, namely the input string, the starting index number, and the ending index number, and outputs a substring.

    Also, the C program that extracts a portion of a string prompts a user to input the string along with the starting and ending index number to extract the substring.

    People are also Reading

    Leave a Comment on this Post

    0 Comments