《C和指针》学习笔记[第9章 字符串、字符和字节]
1.
#define CHAR_SIZE 100 #define NUL '\0' int main(void){ char string[CHAR_SIZE]; fgets(string, sizeof(string)/sizeof(string[0]), stdin); double string_length; int char_num[7] = {0}; string_length = strlen(string); char *p = string; while (*p != NUL) { if (iscntrl(*p)) { char_num[0]++; } if (isspace(*p)){ char_num[1]++; } if (isdigit(*p)){ char_num[2]++; } if (islower(*p)){ char_num[3]++; } if (isupper(*p)){ char_num[4]++; } if (ispunct(*p)){ char_num[5]++; } if (!isprint(*p)){ char_num[6]++; } p++; } printf("string_length = %.0f\n", string_length); printf("cntrl = %d, space = %d, digit = %d, lower = %d, upper = %d, punct = %d no_print = %d\n", char_num[0], char_num[1], char_num[2], char_num[3], char_num[4], char_num[5], char_num[6]); return EXIT_SUCCESS; }
2.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <stdarg.h> #include <ctype.h> #include "t_c.h" #define CHAR_SIZE 100 #define NUL '\0' size_t my_strlen(char *p, int length){ size_t r_length; for (r_length = 0 ; r_length < length; r_length++) { if (p[r_length] == NUL) { break; } } return r_length; } int main(void){ char string[CHAR_SIZE] = "123456"; printf("%lu\n", my_strlen(string, 10)); return EXIT_SUCCESS; }
3.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <stdarg.h> #include <ctype.h> #include "t_c.h" #define CHAR_SIZE 100 #define NUL '\0' char *my_strcpy(char *dst, char *src, int lenght){ char *r_str_point = dst; int i; for (i = 0; i < lenght; i++) { *dst++ = *src++; if (*src == NUL) { break; } } printf("i = %d, lenght = %d\n", i, lenght); if (i == lenght) { r_str_point[i] = NUL; } return r_str_point; } int main(void){ char string[CHAR_SIZE] = "123456"; char dst[CHAR_SIZE]; my_strcpy(dst, string, 30); printf("%s\n", dst); return EXIT_SUCCESS; }
4.
char *my_strcat(char *dst, char *src, int lenght){ char *r_str_point = dst; int i; int c_sign = 0; for (i = 0; i < lenght; i++) { if (*++dst == NUL) { c_sign = 1; } if (c_sign) { *dst = *src++; } if (*src == NUL) { break; } } if (i == lenght) { r_str_point[i] = NUL; } return r_str_point; } int main(void){ char string[CHAR_SIZE] = "123456"; char dst[CHAR_SIZE] = "abc"; my_strcat(dst, string, 5); printf("%s\n", dst); return EXIT_SUCCESS; }
5.