当前位置: 代码迷 >> 综合 >> C程序设计语言 5-5
  详细解决方案

C程序设计语言 5-5

热度:53   发布时间:2024-01-20 04:14:55.0

 练习 5-5 实现库函数strncpy、strncat和strncmp,它们最多对参数字符串中的前n个字符进行操作。例如,函数strncpy(s,t,n)将t中最多前n个字符复制到s中。更详细的说明请参见附录B。

#include <stdio.h>void my_strncpy(char *, char *, int n);
void my_strcat(char *, char *, int n);
int my_strncmp(char *, char *, int n);int main() {char s[50] = "qwert", t[50] = "asdfg", n[50] = "";my_strcat(s, t, 3);my_strncmp(s, t, 6) ? printf("same\n") : printf("notsame\n");my_strncpy(n, t, 4);printf("%s\n", n);printf("%s\n", s);return 1;
}void my_strncpy(char *s, char *t, int n) {    /*copy n characters from string t to string s*/while (--n >= 0 && (*s++ = *t++) != '\0');return;
}void my_strcat(char *s, char *t, int n) {    /*concatenate n characters from string t to string s*/while (*s++ != '\0');s--;while (--n >= 0 && (*s++ = *t++) != '\0');return;
}int my_strncmp(char *s, char *t, int n) {    /* compare n characters of string s andt, return 1 if same, 0 if not.*/int flag = 1;while (--n >=0 && *s != '\0' && *t != '\0') {if (*s++ != *t++)flag = 0;}return flag;
}