c++ 如何得到字符在字符串中第一次出现时候的地址的函数
时间: 2024-03-19 10:44:10 浏览: 17
C++ 标准库中提供了 `std::string` 类型的 `find` 函数,可以用来查找字符串中某个字符或子串第一次出现的位置。该函数返回一个整数,表示该字符或子串在字符串中的下标位置。如果找不到,则返回 `std::string::npos`。
如果要获取该字符或子串在字符串中第一次出现时的地址,可以使用 `std::string` 类型的 `data` 函数,该函数返回字符串内部存储的字符数组的首地址。然后再根据 `find` 函数返回的下标位置,使用指针偏移的方式获取该字符或子串在字符串中第一次出现时的地址。
下面是一个示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
char c = 'o';
size_t pos = str.find(c);
if (pos != std::string::npos) {
char* p = &str[pos];
std::cout << "The address of the first occurrence of " << c << " in \"" << str << "\" is " << (void*)p << std::endl;
} else {
std::cout << "The character " << c << " is not found in \"" << str << "\"" << std::endl;
}
return 0;
}
```
输出结果为:
```
The address of the first occurrence of o in "hello world" is 0x560bfec7c75b
```