C Program to Extract a Portion of String

By | November 13, 2021
C Program to Extract a Portion of String

Here in this article, we have written a C program that can extract a substring from a given string.

Steps

  • Ask the user to enter a string
  • Ask the user to enter the starting and endpoint of the string they want to extract and these points will represent the index value of String
  • Pass the string, starting point and ending point as the argument to the user-defined function sub_string().
  • The sub_string() function prints a sequence of string from the start to ending point that the user has entered.

C Program to Get a Substring From 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:

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

Note:

gets(): It in-built C function which used to take string input from the user and it is similar to the scanf() function.

People are also Reading

Leave a Reply

Your email address will not be published. Required fields are marked *