Pages

  • Home
  • About & Contact
  • Archive
  • C Programming Examples

09 June 2012

c program to extract substring from string using pointers

Here is the program to extract Substring from the given String.


c program to extract substring from string using pointers

I am showing two ways to extract the substring.

First way:

#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
          char og[50],ss[50];
          int x,y,st,len;
          //clrscr();
          printf("Enter the String: ");
          scanf("%s",og);
          printf("Enter the start position and length to be extracted");
          scanf("%d%d",&st,&len);
          for(x=st,y=0;y<len&&og[x]!='\0';x++,y++)
          {
                  ss[y]=og[x];
          }
          ss[y]='\0';
          printf("Your Substring is %s",ss);
          getch();
}


Second way: using Pointer's


#include<conio.h>
#include<stdio.h>
#include<string.h>
void extract(char *,char *,int ,int );
void main()
{
          char og[50],ss[50];
          int x,y,st,len;
          //clrscr();
          printf("Enter the String: ");
          scanf("%s",og);
          printf("Enter the start position and length to be extracted");
          scanf("%d%d",&st,&len);
          extract(og,ss,st,len);                            // 1
          printf("Your Substring is %s",ss);
          getch();
}

void extract(char *str1,char *str2,int s,int l)   // 2
{
         int i;
         str1=str1+(s-1);                                  // 3
         for(i=0; i < l && str1 != '\0' ;i++)                // 4
         {
                   *str2++=*str1++;                     // 5
          }
          *str2='\0';                                          // 6
}


Explanation: Both programs are much similar.So Explaining the second program.Consider the comments //1  //2...
//1: We are calling function extract and passing the variables as base address of the strings og and ss ,and also the start position and length of substring.


//2: Collecting variables in char pointers and integer variables as required.

//3:  Moving the char pointer to point the location that is the start position of substring.

//4: Running the loop according to the length of substring and it should not exceed original string

//5: Copying the contains of original string to substring character by character and increment pointer location.

//6: Adding '\0' at the end of substring to indicate end of string.



Share your views regarding the given post via the comments section given below.
If you liked the post, please '+1' it & share it on other social networks.
Thank You.
Romil Shah


No comments:

Post a Comment

Back To Top