lolamontes69

K+R Exercise5_5

Sep 7th, 2014
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. char *strncpy(char s[],char ct[],int n);
  4. char *strncat(char s[], char ct[], int n);
  5. int strncmp(char cs[], char ct[], int n);
  6.  
  7. int main()
  8. {
  9.     int i;
  10.    
  11.     char s[300]="cute froggy";
  12.     char ct[]="froggy";
  13.     char *sp;
  14.     sp = &s[0];
  15.  
  16.     *sp = *(strncpy(s,ct,4));
  17.  
  18.     printf("What a %s",s);
  19.     puts(" ");
  20.  
  21.     *sp = *(strncat(s,ct,3));
  22.  
  23.     printf("What a %s",s);
  24.     puts(" ");
  25.  
  26.     i = strncmp(s,ct,4);
  27.     printf("strcmp returned %d",i);
  28.     puts(" ");
  29.     return(0);
  30. }
  31.  
  32. /* strncpy:  copy n characters of string ct to s and fill the rest with '\0's */
  33. char *strncpy(char s[],char ct[],int n)
  34. {
  35.     int i;
  36.    
  37.     for(i=0; s[i]!='\0'; i++) {
  38.         if(i>=n)
  39.             s[i]='\0';
  40.         else
  41.             s[i]=ct[i];
  42.     }
  43.     return &s[0];
  44. }
  45.  
  46. /* strncat: concatenate n chars of ct to the end of s, s must be big enough */
  47. char *strncat(char s[], char ct[], int n)
  48. {
  49.     int i=0;
  50.     int j;
  51.  
  52.     while(s[i]!='\0')      /*find end of s */
  53.         i++;
  54.     for(j=0 ; j<n ; i++, j++)
  55.         s[i]=ct[j];
  56.     s[i]= '\0';
  57.     return &s[0];
  58. }
  59.  
  60. /* strncmp: compare n chars at the beginning of ct with n at the beginning of cs
  61.  * return 0 if cs<ct, 0 if cs==ct or >0 if cs>ct */
  62. int strncmp(char cs[], char ct[], int n)
  63. {
  64.     int i;
  65.  
  66.     for(i=0; cs[i] == ct[i]; i++)  
  67.         if(i==n-1)        /* n-1 because count starts at zero */  
  68.             return 0;
  69.     return cs[i] - ct[i];
  70. }
Advertisement
Add Comment
Please, Sign In to add comment