Saturday 15 June 2013

A Program That Extracts Part Of A Given String

I decided to do one of the exercises at the end of Chapter 9 of Let Us C.

D-c:
Write a program that extracts part of the given string from the specified position. For example, if the string is "Working with strings is fun", then if from position 4, 4 characters are to be extracted then the program should return string as "king". If the number of characters to be extracted is 0 then the program should extract entire string from the specified position.

I tried to do it with an array of pointers to strings as opposed to a normal array, although I don't think I needed to.
Sample execution:

Here is my attempt:

#include <stdio.h>
#include <strings.h>
#include <stdlib.h>

main()
{
    char *arr1,str[100],*temp;
    int start,ends,len,i;

    printf("Enter a length of string: \n");
    gets(str);
    len=strlen(str);
    temp=(char *)malloc(len+1);
    strcpy(temp,str);
    arr1=temp;

    printf("Where will the extraction begin from (Less than %i): \n",len);
    scanf("%i",&start);
    if(start<len && start>0)
    {
        start=start-1;

        printf("How many characters do you want to extract?(less than or equal to %i)?\n",len-start);
        scanf("%i",&ends);
        if(ends<=len && ends>0)
        {
            arr1[start+ends]='\0';
            arr1=arr1+start;

            printf("%s",arr1);
        }

        else if(ends==0)
        {
            i=start;
            while(arr1[i]!='\0')
            {
                printf("%c",arr1[i]);
                i++;
            }
        }

        else
        {
            printf("Invalid Input.");
        }
    }
    else
    {
        printf("Invalid Input!");
    }
}


1 comment: