c++ find函数
时间: 2023-06-03 20:05:55 浏览: 84
请问您需要使用哪种编程语言来使用 find 函数?如果是使用 C++,那么可以使用 string 类的 find 函数,例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
int pos = str.find("world");
std::cout << pos << std::endl; // output: 6
return 0;
}
```
如果是使用 C 语言,则可以使用 strstr 函数,例如:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char *ptr = strstr(str, "world");
printf("%d\n", ptr - str); // output: 6
return 0;
}
```
注意,以上程序中的 find 函数都是用于查找一个子字符串在另一个字符串中第一次出现的位置。如果找不到该子字符串,则返回一个特殊的值,例如 C++ 中的 std::string::npos,或者 C 语言中的 NULL。另外,这些函数都是区分大小写的,如果要忽略大小写,可以使用类似 strcasestr 的函数(C 语言)、std::string::find_first_of(C++)等等。
相关问题
c++ find函数
在C++的STL库中,有很多用于字符串操作的函数。其中,find()函数用于查找某个字符或子串在字符串中的位置。 find()函数是全匹配的,也就是说它会查找完整的子串,并返回第一次匹配到的位置。如果找到了匹配的子串,它会返回子串在字符串中的起始位置;如果找不到匹配的子串,它会返回-1。 具体使用方法可以参考以下示例代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "adedef";
string s2 = "dek";
int ans = s1.find(s2); //在s1中查找子串s2
cout << ans << endl;
return 0;
}
在上述代码中,s1.find(s2)的返回值即为子串s2在s1中第一次出现的位置。如果找不到匹配的子串,返回-1。
c++find函数
C++ 中的 `find()` 函数是在一个容器中查找指定元素的函数。它可以用于许多不同的容器,如 vector、list、set 等。
`find()` 函数通常的用法是:
```c++
auto it = std::find(container.begin(), container.end(), value);
```
其中,`container` 是容器对象,`begin()` 和 `end()` 是容器的迭代器,`value` 是要查找的值。`find()` 函数返回一个迭代器,指向第一个匹配 `value` 的元素,如果没有找到,则返回容器的 `end()` 迭代器。
示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v{1, 2, 3, 4, 5};
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
std::cout << "Found " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出为:
```
Found 3
```