用指针访问std ::字符串中的元素
Accessing elements in a std::string with pointers
如何使用指针访问std :: string中的单个元素?如果没有类型铸造到const char *?
#include <iostream>
#include <string>
using namespace std;
int main() {
// I'm trying to do this...
string str = "This is a string";
cout << str[2] << endl;
// ...but by doing this instead
string *p_str = &str;
cout << /* access 3rd element of str with p_str */ << endl;
return 0;
}
有两种方法:
-
明确调用
operator[]
函数:std::cout << p_str->operator[](2) << 'n';
或使用
at
功能std::cout << p_str->at(2) << 'n';
这两个都是几乎等效的。
-
或取消指针获取对象,并使用正常索引:
std::cout << (*p_str)[2] << 'n';
无论哪种方式,您都需要取消指针。通过"箭头"操作员->
或使用直接取消运算符*
无关紧要。
相关文章:
- 是否可以在c++中处理字符串流中的各个元素
- 如何将元素添加到向量的字符串位置
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 将包含多个元素的字符串作为输入并转换为矢量 C++
- 如何计算字符串中用户输入元素的出现次数?
- C++ 查找字符串中存在的元素向量
- 如何将凯撒密码的元素从字符串更改为字符串
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 用字符串 c++ 比较对向量的元素
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 将字符串集合中的元素添加到字符串集合的向量中
- 如何将字符串加载到BYTE*数组(C++)的元素中
- 需要从字符串数组的一部分访问元素
- 如何打印出常量字符串的第一个元素?
- 如何使用libxml2从C 中的XML文件中检索节点和特定元素字符串而不使用XPATH
- 如何使用XPath使用libxml2从C 中的XML文件中检索节点和特定元素字符串
- 添加元素<字符串、指针>以提升无序哈希图