Guest User

Untitled

a guest
Jul 15th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. // substring.c
  6. // compile with: gcc -o substring substring.c
  7. // run with: ./substring "input string" start_index end_index
  8.  
  9. int main(int argc, char **argv) {
  10. // argv[1] is the inputted string // first argument
  11.  
  12. // atoi(); is a function that converts strings to integers; refer to `man 3 atoi'
  13. int start = atoi(argv[2]); // second argument; start position
  14. int end = atoi(argv[3]); // third argument; end position
  15.  
  16. // allocate space for our inputted string.
  17. char *string = malloc(sizeof(char) * (strlen(argv[1]) + 1));
  18.  
  19. // copy input string to working string
  20. strcpy(string,argv[1]);
  21.  
  22. // allocate space for our partial string
  23. char *str = malloc(sizeof(char) * end);
  24.  
  25. // the magic
  26. strncpy(str,&(string[start]),end);
  27.  
  28. // and the goods.
  29. printf("input string = \"%s\"; start: %d; end: %d; returned string = \"%s\";\n",argv[1],start,end,str);
  30.  
  31. return EXIT_SUCCESS;
  32. }
Add Comment
Please, Sign In to add comment