Tuesday, May 28, 2013

Find the substring of a given input string

Given a string . If you are given a specified position and the number of characters , then find a substring from that specified position and having the given number of characters in it from the input string given.

Following is the code .

// program to find a substring of a given string
//if specified position is given and number of characters is 0 , then the entire string is printed from the specified posiition

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

char *substring(char *str,int i , int n)
{

    char *substr ;
    int k ;

    if(n==0)
        n = strlen(str) - i ;

    substr = (char *)malloc(n+1);

    while(n>0)
    {
        substr[k++] = str[i-1];
        i++;
        n--;
    }
    substr[k] = '\0';
    printf("\n%s",substr);

    return substr;
}

int main()
{
    char input[100] ;
    int i , j ; 
    printf("\nEnter the input String : ");
gets(input); printf("\nEnter the position : "); scanf("%d",&i); printf("\nEnter the number of characters : "); scanf("%d",&j); printf("\n%s",substring(input,i,j)); }