strstr和memcmp函数的实现
生活随笔
收集整理的這篇文章主要介紹了
strstr和memcmp函数的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <stdio.h>
#include <stdlib.h> //malloc()函數
typedef unsigned int size_t;size_t my_strlen(const char * str)
{const char *sc = NULL;if(str == NULL)return 0;for(sc = str;*sc != '\0';sc++){/* do nothing */} return sc - str;
}/* 因為類型可以為任意,所以形參應為void ** 相等則返回0,否則不為0*/
int my_memcmp(const void *s1,const void *s2,size_t count)
{int res = 0;const unsigned char *p1 =(const unsigned char *)s1;//注意是unsigned char *const unsigned char *p2 =(const unsigned char *)s2; for(p1 ,p2;count > 0;p1++,p2++,count--)if((res =*p1 - *p2) != 0) //不相當則結束比較break;return res;
}
/* 查找字符串s2是否為s1的子串,s1為主串* 如果是則返回從第一個子串開始的字符串 */
char * my_strstr(const char *s1,const char *s2)
{int len1,len2;len2 = my_strlen(s2); //獲取子串s2的長度if(!len2) //如果子串s2為空則返回s1return (char *)s1; //先強制類型轉換len1 = my_strlen(s1); //獲取子串s1的長度while(len1 >= len2){len1--;if(!my_memcmp(s1,s2,len2)) //my_memcmp返回0表示s1中存在s2的子串return (char *)s1; //先強制類型轉換s1++;}return NULL; //len1 < len2時返回空
}int main()
{printf("%s\n",my_strstr("hello world","world"));printf("%s\n",my_strstr("hello world","e"));printf("%s\n",my_strstr("hello world","llo"));return 0;
}
執行結果:
2013年10月10日17:23分補充下面算法
不使用庫函數來實現strstr函數,效率其實也不高,高效率應該使用KMP法
?
#include <stdio.h>char* strstr(char* buf, char* sub) {char* bp;char* sp;if(sub == NULL)return buf;while(buf !=NULL){bp=buf;sp=sub;do{ if(!*sp) //sp到最后即sub到最后則返回第一個子串在主串的位置return buf;}while(*bp++ == *sp++);buf++; //如果不等,主串buf+1,子串回溯到0}return 0; }int main() {printf("%s\n",strstr("hello world", "ell"));return 0; }執行結果:
?
?
轉載于:https://www.cnblogs.com/suncoolcat/p/3362333.html
總結
以上是生活随笔為你收集整理的strstr和memcmp函数的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: modelsim仿真
- 下一篇: 页面上有两个元素id相同,js中如何取值