《c程序设计语言》读书笔记-5.5-指针实现strncpy,strncat,strncmp
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <curses.h> void strncpy_(char *s,char *t,int n) { while(*t && n-- > 0) *s++ = *t++; while(n-- > 0) *s++ = '\0'; } void strncat_(char *s,char *t,int n) { while(*s) s++; while((*s++ = *t++) && n-- > 0) ; } int strncmp_(char *s,char *t,int n) { for( ; *s == *t;s++,t++) if(*s == '\0' || --n <= 0) return 0; return *s - *t; } int main() { char *c = "Ilove you!";; char *p = "Ilpe ni!" ; int n = 3; int i; i = strncmp_(c,p,n); printf("%d",i); return 0; }
主函数调用strncmp,该函数返回字符串ASCII码差值。