如何用c++得到一个字符串在另一个字符串中第一次出现的地址
时间: 2024-03-20 08:38:54 浏览: 20
你可以使用C++中的`std::string`和`std::string::find()`函数来实现。具体步骤如下:
1.定义两个`std::string`类型的变量,分别存储要查找的字符串和目标字符串。
2.使用`std::string::find()`函数查找要查找的字符串在目标字符串中第一次出现的位置。
3.如果找到了,返回该位置的地址;否则返回空指针。
下面是示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::string target = "wor";
// 查找目标字符串在 str 中第一次出现的位置
size_t pos = str.find(target);
if (pos != std::string::npos) {
std::cout << "Target string found at position: " << pos << std::endl;
std::cout << "Address of target string: " << &str[pos] << std::endl;
} else {
std::cout << "Target string not found in source string." << std::endl;
}
return 0;
}
```
输出结果为:
```
Target string found at position: 6
Address of target string: 0x7ffc4b3d2a7a
```