模拟实现strstr函数
时间: 2023-03-10 08:59:18 浏览: 97
我可以用以下算法来模拟实现strstr函数:
1. 使用双重循环,从字符串中搜索目标字符串,如果找到,返回下标;
2. 使用KMP算法,搜索字符串,如果找到,返回下标;
3. 使用暴力匹配法,逐个比较源字符串和目标字符串,如果找到,返回下标。
相关问题
模拟实现strstr
strstr函数是C语言中的字符串查找函数,用于在一个字符串中查找指定的子串,并返回子串在原字符串中的起始位置。
以下是一个简单的模拟实现strstr函数的代码:
```c
#include <stdio.h>
#include <string.h>
char* my_strstr(const char* haystack, const char* needle) {
if (*needle == '\0') {
return (char*) haystack; // needle为空串,直接返回haystack
}
for (; *haystack != '\0'; haystack++) {
const char* h = haystack;
const char* n = needle;
while (*n != '\0' && *h == *n) {
h++;
n++;
}
if (*n == '\0') {
return (char*) haystack; // 子串匹配成功
}
}
return NULL; // 未找到子串
}
int main() {
char haystack[] = "Hello, World!";
char needle[] = "World";
char* result = my_strstr(haystack, needle);
if (result == NULL) {
printf("Substring not found.\n");
} else {
printf("Substring found at index: %ld\n", result - haystack);
}
return 0;
}
```
这段代码实现了一个自定义的my_strstr函数,功能与C标准库中的strstr函数相同。它通过逐个比较字符,找到子串在原字符串中的起始位置,或者返回NULL表示未找到。
注意:此处只是简单模拟实现,实际的strstr函数可能会更加复杂和优化。
模拟strstr函数查找子串
可以使用循环逐一比较子串和字符串中的每个字符,如果匹配成功,则返回当前位置,否则继续往后查找,直到字符串末尾。
以下是一个示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int strStr(char *haystack, char *needle) {
if (*needle == '\0') return 0;
int len1 = strlen(haystack);
int len2 = strlen(needle);
for (int i = 0; i < len1 - len2 + 1; i++) {
int j = 0;
for (; j < len2; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == len2) {
return i;
}
}
return -1;
}
int main() {
char s1[] = "hello world";
char s2[] = "world";
int pos = strStr(s1, s2);
cout << pos << endl; // 6
return 0;
}
```
在上面的代码中,我们首先判断 needle 是否为空串,如果是,则直接返回 0,因为空串是任何字符串的子串。接着,我们使用两个变量 len1 和 len2 分别记录字符串 haystack 和 needle 的长度。然后,我们从字符串 haystack 的第一个字符开始,逐一比较 haystack 和 needle 中的字符,如果匹配成功,则返回当前位置 i,否则继续往后查找,直到字符串末尾。如果找不到,则返回 -1。