比较字符串
- C/C++ code
#include <stdio.h>#include <string.h>#define LEN 30char * string_in(const char *,const char *);int main(void){ char str1[LEN] = "still loving you"; char str2[LEN/2]; char * find; puts(str1); puts("Please enter str2(empty line to quit)"); while(gets(str2) != NULL && str2[0] != '\0') { find = string_in(str1,str2); if(find) puts(find); else puts("No found"); } puts("Bye"); return 0;}char * string_in(const char * s1,const char * s2){ int x = 1; int l2 = strlen(s2); int l3 = strlen(s1) + 1 - l2; if(l3 > 0) while((x = strncmp(s1,s2,l2)) && l3--) s1++; if(x) return NULL; else return (char *)s1;}如果输入S1,长度大于S1,比如:
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
结果是
No found
如果再接着输入yo
结果还是
No found
而不是预想的you
点解?
[解决办法]
代码有潜在的问题,即如果str2输入的数据超过15个那么就是内存溢出了。如果内存溢出,对于字符串的结束符就不复存在了。这样下面的比较就没有意义了,因为你掉用了strcmp,需要有'\0'结束符的。
但如果是输入的是小于15个字符,就没有问题。对于gets的使用,不如使用fgets(str2, LEN/2 - 1, stdin);
[解决办法]
gets最好少用,定义指针的时候最好先置为NULL。
[解决办法]
gets(str2)
改为
fgets(str2,LEN/2,stdin)
[解决办法]