strstr 字符串中包含0x00
时间: 2023-07-24 16:09:35 浏览: 166
strstr函数在查找字符串的过程中会遇到字符串中包含0x00的情况。因为C语言中的字符串是以0x00作为结束符的,所以如果字符串中包含0x00,则会被当作字符串的结束符而导致查找中断。
解决这个问题的方式是使用另外一个C库函数memcmp来进行查找。memcmp函数会比较两个指定长度的内存块,其函数原型为:
```c
int memcmp(const void *s1, const void *s2, size_t n);
```
其中,s1和s2分别表示要比较的两个内存块的指针,n表示要比较的字节数。函数返回值为一个整数,如果s1和s2相等则返回0,如果s1小于s2则返回负数,如果s1大于s2则返回正数。
因此,要在一个字符串中查找另一个字符串并且字符串中可能包含0x00,可以使用如下代码:
```c
char *haystack = "hello\x00world";
char *needle = "world";
int hay_len = strlen(haystack);
int ned_len = strlen(needle);
char *pos = NULL;
for (int i = 0; i <= hay_len - ned_len; i++) {
if (memcmp(haystack + i, needle, ned_len) == 0) {
pos = haystack + i;
break;
}
}
if (pos != NULL) {
printf("Found at position %ld\n", pos - haystack);
} else {
printf("Not found\n");
}
```
输出结果为:
```
Found at position 6
```
表示在字符串"hello\x00world"中找到了"world"子字符串,并且忽略了0x00的影响。