Added cbd_rand. Generates x random numbers in y columns. Interactive program.
[C-Programming-Examples.git] / ex_5-5.c
blob69fff2046e92d52b919381f176ff7e4d6c7c52d7
1 #include <string.h>
2 #include <stdio.h>
4 /* print contents of array */
5 void print_array(char s[])
7 int i;
8 for(i = 0; i < strlen(s); i++)
9 printf("%c", s[i]);
10 printf("\n");
15 Copy at most n chars of string source into string dest.
16 Pad with '\0' if source has fewer chars than dest.
19 char *ss_strncpy(char *dest, const char *source, int n)
21 char *d = dest;
22 if(n >= 0 || n == '\0')
24 while(--n >= 0 && (*dest++ = *source++) != '\0')
25 continue;
26 while(--n > 0)
27 *dest++ = '\0';
30 return d;
35 Appends n chars of src into the end of dest.
37 If null encountered before n, then copy null and no more.
39 If n is zero or negative, then function has not effect.
42 char *ss_strncat(char *dest, const char *source, size_t n)
44 while(*dest) { ++dest; } // find pointer val for end of string s
45 while((--n >= 0) && (*dest++ = *source++) != '\0');
46 return dest;
51 Compares contents of string s1 with contents of s2.
53 If s1 < s2 returns < 0
54 If s1 == s2 returns 0
55 If s1 > s2 returns > 0
58 int ss_strncmp(const char *s1, const char *s2, size_t n)
61 while(--n >= 0 && *s1 != '\0' && *s2 != '\0')
64 if(*s1++ == *s2++) { continue; }
65 if(*s1 > *s2)
66 return 1;
67 else
68 return -1;
70 return 0;
73 int main()
75 char source[] = { "Destination after..." };
76 char dest[] = { "This is the destination before..." };
78 print_array(dest);
80 char *ans;
82 ans = strncpy(dest, source, 20);
84 printf("%p\n", ans);
85 print_array(dest);
87 printf("\n\n");
89 char source2[] = { "Destination after..." };
90 char dest2[] = { "This is the destination before..." };
92 print_array(dest2);
94 ss_strncpy(dest2, source2, 20);
96 printf("%p\n", ans);
97 print_array(dest2);
99 char info[] = { "Data To Append. " };
100 char buffer[50] = { "Beginning of Buffer. " };
101 int i;
102 for(i = 0; i <= 2; ++i)
104 strncat(buffer, info, strlen(info));
105 print_array(buffer);
108 printf("\n");
110 char smaller[] = { "12345" };
111 char bigger[] = { "67890" };
112 int size_ans;
114 size_ans = ss_strncmp(smaller, bigger, 3);
115 printf("%d\n", size_ans);
117 size_ans = ss_strncmp(bigger, bigger, 3);
118 printf("%d\n", size_ans);
120 size_ans = ss_strncmp(bigger, smaller, 3);
121 printf("%d\n", size_ans);
123 return 1;