This blog is under construction

Tuesday 16 July 2013

C program to copy specific portion of string

Write a C program to copy specific portion of string.


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

  int main() {
        char input[256], output[255], *ptr;
        int start, end, i = 0;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(input, 256, stdin);
        input[strlen(input) - 1] = '\0';

        /* get the position to copy specific portion of string */
        printf("Enter the start and end location to copy(0-n):");
        scanf("%d%d", &start, &end);

        /* bourndary check */
        if (start < 0 || start > end ||
                end < start || end > strlen(input) -1 ) {
                printf("Error in copying!!\n");
                return 0;
        }

        /* move pointer to the start location */
        ptr = input + start;

        /* copy requested portion of string */
        while (start <= end) {
                output[i] = input[start];
                i++;
                start++;
        }

        /* Null termination */
        output[i] = '\0';

        /* print the output */
        printf("Resultant String: %s\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:Thanks For Visiting My Blog
  Enter the start and end location to copy(0-n):0 6
  Resultant String: Thanks 


1 comment:

  1. Hi! Would you be able to write a code to print the nth character from a text file?

    ReplyDelete