c++中没有find函数
时间: 2023-12-16 17:05:53 浏览: 32
,但可以使用字符串库中的strstr函数来查找某个子字符串在另一个字符串中的位置。例如:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World!";
char *substr = "World";
char *pos = strstr(str, substr);
if (pos != NULL) {
printf("'%s' is found at position %ld\n", substr, pos - str);
} else {
printf("'%s' is not found\n", substr);
}
return 0;
}
```
输出:
```
'World' is found at position 6
```
相关问题
C++中的find函数
C语言中的find函数通常不是内置函数,而是由程序员自己编写的函数。该函数的作用是在字符串中查找指定字符或字符串,并返回第一个匹配的位置。具体实现方式可以有多种,以下是一种简单的实现:
```
int find(char *str, char *sub)
{
int i, j;
for (i = 0; str[i] != '\0'; i++) {
for (j = 0; sub[j] != '\0'; j++) {
if (str[i+j] != sub[j])
break;
}
if (sub[j] == '\0')
return i;
}
return -1;
}
```
该函数接收两个字符串参数,分别是要查找的字符串和要查找的子字符串。函数首先在要查找的字符串中进行循环,逐个字符地比较是否与子字符串匹配。如果有不匹配的字符,则退出内层循环,并继续在下一个位置进行匹配。如果匹配成功,则返回当前位置。如果循环结束后仍未找到匹配,则返回-1。
c++中find函数讲解
在 C 语言中,没有内置的 find() 函数,但可以通过编写自定义函数来实现相同的功能。
一种实现方式是利用 strstr() 函数,该函数用于在字符串中查找子字符串,并返回第一次出现的位置。因此,可以编写一个函数来利用该函数查找一个字符或字符串在另一个字符串中的位置。
以下是一个示例函数来查找一个字符在字符串中的位置:
```
#include <stdio.h>
#include <string.h>
int find_char(char *str, char ch) {
char *p = strchr(str, ch);
if (p != NULL) {
return p - str;
}
return -1;
}
int main(void) {
char str[50] = "Hello, world!";
int pos = find_char(str, 'o');
if (pos != -1) {
printf("Found at position %d\n", pos);
} else {
printf("Not found\n");
}
return 0;
}
```
输出结果为:Found at position 4
同样,可以编写一个函数来查找一个字符串在另一个字符串中的位置:
```
#include <stdio.h>
#include <string.h>
int find_string(char *str, char *substr) {
char *p = strstr(str, substr);
if (p != NULL) {
return p - str;
}
return -1;
}
int main(void) {
char str[50] = "Hello, world!";
int pos = find_string(str, "world");
if (pos != -1) {
printf("Found at position %d\n", pos);
} else {
printf("Not found\n");
}
return 0;
}
```
输出结果为:Found at position 7
这些示例函数可根据需要进行修改,以实现更特定的查找功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)