帮我用C语言写一个查找字符串的函数
时间: 2023-05-18 10:04:53 浏览: 65
当然可以,以下是一个简单的查找字符串的函数:
```c
#include <stdio.h>
#include <string.h>
int find_string(char *str, char *substr) {
int len1 = strlen(str);
int len2 = strlen(substr);
int i, j;
for (i = 0; i <= len1 - len2; i++) {
for (j = 0; j < len2; j++) {
if (str[i+j] != substr[j]) {
break;
}
}
if (j == len2) {
return i;
}
}
return -1;
}
int main() {
char str[] = "hello world";
char substr[] = "world";
int index = find_string(str, substr);
printf("The index of '%s' in '%s' is %d\n", substr, str, index);
return 0;
}
```
这个函数会在字符串 `str` 中查找子字符串 `substr`,并返回子字符串在字符串中的位置。如果找不到,则返回 -1。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)