Our website is made possible by displaying online advertisements to our visitors.Please consider supporting us by disabling your ad blocker.
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Translate it in your own Language

Print this Job Post

Print Friendly and PDF

Friday, May 30, 2014

Substring in c programming, c substring

C substring code

#include <stdio.h>
#include<conio.h>
#include <malloc.h>
char* substring(char*, int, int);
void main() 
{
   char string[100], *pointer;
   int position, length;
   clrscr();
   printf("Enter a string\n");
   gets(string);
   printf("Enter the position and length of substring\n");
   scanf("%d%d",&position, &length);
   pointer = substring( string, position, length);
   printf("Required substring is \"%s\"\n", pointer);
   free(pointer);
   getch();
}
/*C substring function: It returns a pointer to the substring */
char *substring(char *string, int position, int length) 
{
   char *pointer;
   int c;
   pointer = malloc(length+1);
   if (pointer == NULL)
   {
      printf("Unable to allocate memory.\n");
      exit(EXIT_FAILURE);
   }
   for (c = 0 ; c < position -1 ; c++) 
   string++; 
   for (c = 0 ; c < length ; c++)
   {
      *(pointer+c) = *string;      
      string++;   
   }
  *(pointer+c) = '\0';
  return pointer;
}

Output of program:


C code for all substrings of a string

#include <stdio.h>
#include <string.h>
#include<conio.h>
#include <malloc.h>
char* substring(char*, int, int);
void main() 
{
   char string[100], *pointer;
   int position = 1, length = 1, temp, string_length;
   clrscr();
   printf("Enter a string\n");
   gets(string);
   temp = string_length = strlen(string);
   printf("Substring of \"%s\" are\n", string);
   while (position <= string_length)
   {
      while (length <= temp)
      {
         pointer = substring(string, position, length);
         printf("%s\n", pointer);
         free(pointer);
         length++;
      }
      temp--;
      position++;
      length = 1;
   }
  getch();
}

Output of program:




No comments:

Post a Comment

Copyright @ CrackMNC 2014-2024
Divas Nikhra Theme by Crack MNC