training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

mystrcnp.c (1789B)


      1 /* Exercise 8.28 */
      2 
      3 #include <stdio.h>
      4 #include <string.h>
      5 
      6 char *strcpy(char *s1, const char *s2);
      7 char *strncpy(char *s1, const char *s2, size_t n);
      8 char *strcat(char *s1, const char *s2);
      9 char *strncat(char *s1, const char *s2, size_t n);
     10 
     11 int main(void)
     12 {
     13    char string1[50] = "this is the first string";
     14    char string2[] = " and this is the 2nd :-)";
     15 
     16    printf("BeFoRe\n\tstring1[] = %s\n\tstring2[] = %s\n", string1, string2);
     17 
     18    /* Insert the function here */
     19 
     20    printf("\naFTeR\n\tstring1[] = %s\n\tstring2[] = %s\n", string1, string2);
     21 
     22 
     23    return 0;
     24 } /* E0F main */
     25 
     26 /* Copy s2 to s1 and return s1 */
     27 char *strcpy(char *s1, const char *s2)
     28 {
     29    int i;
     30 
     31    for(i = 0; ( s1[i] = s2[i] ) != '\0'; i++);
     32 
     33    /* Second version 
     34       for(i = 0; ( *(s1 + i) = *(s2 + i) ) != '\0'; i++);
     35    */
     36 
     37    return s1;
     38 
     39 } /* eof strcpt(1) */
     40 
     41 /* Copy n characters from s2 to s1 and return s1 */
     42 char *strncpy(char *s1, const char *s2, size_t n)
     43 {
     44    int i;
     45 
     46    for(i = 0; i < (int)n; i++) {
     47       if( ( s1[i] = s2[i] ) == '\0' )
     48       /* Second version
     49       if( ( *(s1 + i) = *(s2 + i) ) == '\0' )
     50       */
     51 	 break;
     52    }
     53 
     54    return s1;
     55 } /* eof strncpy() */
     56 
     57 /* Append s2 to s1 and return s1 */
     58 char *strcat(char *s1, const char *s2)
     59 {
     60    int i, j = (int)strlen(s1);
     61 
     62    for(i = 0; ( s1[j + i] = s2[i] ) != '\0'; i++); 
     63    /* Second version
     64    for(i = 0; ( *(s1 + j + i) = *(s2 + i) ) != '\0'; i++); 
     65    */
     66 
     67    return s1;
     68 } /* eof strcat() */
     69 
     70 /* Append n characters from s2 to s1 and return s1 */
     71 char *strncat(char *s1, const char *s2, size_t n)
     72 {
     73    int i, j = (int)strlen(s1);
     74 
     75    for(i = 0; i < (int)n; i++) {
     76       if( (s1[i + j] = s2[i]) == '\0')
     77       /* Second version
     78       if( ( *(s1 + i + j) = *(s2 + i) ) == '\0')
     79       */
     80 	 break;
     81    }
     82 
     83    return s1;
     84 } /* eof strncat() */
     85