c语言中部分限制字符函数的实现strncmp,strncat,strncpy,strstr,strrstr

来源:互联网 发布:监控用网络光端机 编辑:程序博客网 时间:2024/05/22 05:06

1、带限制的字符串比较函数的实现

#include<stdio.h> int my_strncmp(char *p, char *q, int n) { int count = 0; while ((*p == *q)&&(count < n)) { *p++; *q++; count++; } if (*p == *q) { return 0; } else { return (*p-*q); }  } int main() { char a[] = "abcdef"; char b[] = "abchkhkhk"; int ret = strncmp(a, b, 4); /*int ret = my_strncmp(a,b,4);*/ if (ret == 0) { printf("a和b相等"); } else if (ret > 0) { printf("a比b大"); } else { printf("a比b小"); } return 0; }


2、带限制的字符串追加函数的实现

#include <stdio.h> void my_strncat(char *p, const char *q,int n) { int count = 0; while (*p) { *p++; } while ((*p++ = *q++)&&(count < n-1)) { count++; } } int main() { char a[30] = "hello "; char b[] = "abcdefghijklmnopqrstuvwxyz"; int i = 0; my_strncat(a, b, 5); printf("%s",a); return 0; }


3、带限制的字符串拷贝函数的实现

#include <stdio.h> void my_strncpy(char *p, char *q, int n) { int count = 0; while ((*p++ = *q++)&&(count < n-1)) { count++; } } int main() { char a[20] = "abcdeilajdkfjkl"; char b[] = "fghijsdfsdfsdfses"; my_strncpy( a, b, 4); printf("%s",a); return 0; }


4、在字符串中找第一次出现的子串

#include<stdio.h> #include <string.h> char *my_strchr(const char* p, const char *q) { while ((*p)&&(*p != *q)) { *p++; } while (*p == *q) {  *p++; *q++;  } if (*q=='\0') { return (char*)p;  } return NULL;     } int main() { char a[] = "theworldisverybeautiful"; char *p = my_strchr(a, "world"); printf("%s",p); return 0; }


5、在字符串中找最后一次出现的子串

#include<stdio.h>char *my_strrchr(const char *p, const char *q){char *start = NULL;char *last = (char*)p;int i = 0;while (*p && *q){start = (char*)p;while((p)&&(q[i])&&(*p == q[i])){p++;i++;}if (q[i] == '\0'){last = start;}p = start + 1;i = 0;}if (*p == '\0'){return last;}else{return NULL;}}int main(){char a[] = "hashdhyshuhysahhhyshkhyshnkhjk";char *p = my_strrchr(a, "ys");printf("%s",p);return 0;}


阅读全文
0 0