home *** CD-ROM | disk | FTP | other *** search
/ Piper's Pit BBS/FTP: ibm 0000 - 0009 / ibm0000-0009 / ibm0003.tar / ibm0003 / LCNOW2.ZIP / EXAMPLES / SUBSTR.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-07-15  |  1.6 KB  |  74 lines

  1. /*
  2.  * S U B S T R
  3.  *
  4.  * Extract a substring from a source string.
  5.  */
  6.  
  7. void CopySubstring(char [], int, int, char []);
  8.  
  9. #define MAXSTR  100
  10.  
  11. int
  12. main(void)
  13. {
  14.     char str1[MAXSTR];      /* input buffer */
  15.     char str2[MAXSTR];      /* substring buffer */
  16.     int i;                  /* array index */
  17.     int spos;               /* starting index */
  18.     int len;                /* requested length */
  19.  
  20.     /*
  21.      * Get the user's input.
  22.      */
  23.     printf("Enter the source string: ");
  24.     gets(str1);
  25.     printf("Enter starting index: ");
  26.     scanf("%d", &spos);
  27.     printf("Enter substring length: ");
  28.     scanf("%d", &len);
  29.  
  30.     /*
  31.      * Extract the substring.
  32.      */
  33.     CopySubstring(str1, spos, len, str2);
  34.  
  35.     /*
  36.      * Display the result.
  37.      */
  38.     if (strlen(str2) > 0)
  39.         printf("Substring = %s\n", str2);
  40.     else
  41.         puts("Empty substring--check your input values");
  42.  
  43.     return (0);
  44. }
  45.  
  46.  
  47. /*
  48.  * CopySubstring()
  49.  *
  50.  * Extract a substring out of a source string.  Copy from the
  51.  * specified starting point until the requested number of characters
  52.  * is copied or the end of the source string is reached.
  53.  */
  54.  
  55. void
  56. CopySubstring(char source[], int start, int count, char result[])
  57. {
  58.     int i;        /* index */
  59.  
  60.     /*
  61.      * If the starting point is within the string, copy
  62.      * characters from the source string to the result string.
  63.      */
  64.     if (start >= 0 && strlen(source) > start)
  65.         for (i = 0; i < count && source[start + i] != '\0'; ++i)
  66.             result[i] = source[start + i];
  67.  
  68.     /*
  69.      * Apply a string termination. Also supplies
  70.      * bounds check for invalid input.
  71.      */
  72.     result[i] = '\0';
  73. }
  74.