字符串中单个字符作为数组的数据类型是什么
What is the data type of a single character in a string as an array?
string s;
cin>>s;
假设 s = "堆栈溢出"
现在如果我们访问 s[3]
,它应该发出'c'
s[3]
是'c'
还是"c"
?
就像它是 char 数据类型还是字符串数据类型?
std::string
不是内置类型,因此 s[3]
中的运算符[]
是对字符串模板中定义此运算符的成员函数的调用。
您可以通过查找operator []
的参考页面来找到该类型:
返回对指定位置处字符的引用。
若要从文档中查找类型reference
和const_reference
,请参阅模板std::basic_string<CharT>
"成员类型"部分。
如果要查找从位置 3 开始的长度为 1 的std::string
,请改用substr
:
s.substr(3, 1); // This produces std::string containing "c"
它返回对字符的引用,因为运算符[]
被重载std::string
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
字符"cs[3]是"C"还是"C"?
",而不是字符串"c"。
最容易记住的是,std::string
不像 char
那样是本机类型,而是一个包装class
,其中包含用于形成字符串的chars
数组。
std::string
只是重载 C 数组运算符 [] 以返回给定索引处的char
,因此:
s[3]
会'c'
还是"c"
?答:
'c'
相关文章:
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 很好的语法来获取对向量/数组数据的大小引用?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 数组数据以错误的方式遍历 Python/Matlab
- 访问 Arduino 中的结构数组数据
- 多维数组的类型、名称是什么?
- 在能够从 Web 浏览器访问大型数组数据的同时存储它的最可行方法是什么?
- 共享_ptr中多功能数组的类型是什么
- 在C 类中声明数组数据
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何在 c++ 中将字符串数组数据写入输出文件
- 使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序
- 检索字符数组数据时出现问题
- 数组的类型无效
- 以符合标准的方式用与数组相同类型的成员重新解释结构
- 共享库的C 访问数组数据
- 从数组的类型中找到元素的类型
- 如何在 c++ 中将字节类型的字符数组数据保存到文件中
- 数组数据类型声明