实现 strStr()
时间: 2023-11-27 07:02:36 浏览: 31
strStr() 函数是一个字符串查找函数,用于在一个字符串中查找指定子串的位置。下面是一个简单的实现示例:
```python
def strStr(haystack, needle):
if not needle:
return 0
n = len(haystack)
m = len(needle)
for i in range(n - m + 1):
j = 0
while j < m and haystack[i+j] == needle[j]:
j += 1
if j == m:
return i
return -1
```
这个函数接受两个参数:`haystack` 表示待搜索的字符串,`needle` 表示要查找的子串。它会返回子串在字符串中的起始位置,如果找不到则返回 -1。
该函数使用双重循环进行搜索,外层循环遍历字符串,内层循环逐个字符进行比较。当找到与子串相匹配的字符序列时,返回起始位置。如果遍历完整个字符串仍未找到匹配的子串,则返回 -1。
注意:这只是一个简单的实现示例,实际上,我们可以使用更高效的字符串匹配算法来实现 strStr() 函数。
相关问题
实现strstr
实现strstr函数,即在一个字符串中查找另一个字符串出现的位置。如果找到,返回第一次出现的位置;如果没有找到,返回-1。以下是一个简单的实现:
```java
public static int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
int h = haystack.length(), n = needle.length();
for (int i = 0; i <= h - n; i++) {
int j;
for (j = 0; j < n; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == n) {
return i;
}
}
return -1;
}
```
其中,haystack是要查找的字符串,needle是要查找的子字符串,返回值为子字符串在字符串中的起始位置。
模拟实现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函数可能会更加复杂和优化。