字符串中单个字符作为数组的数据类型是什么

What is the data type of a single character in a string as an array?

本文关键字:数组 数据类型 是什么 单个 字符 字符串      更新时间:2023-10-16
string s;
cin>>s;

假设 s = "堆栈溢出"

现在如果我们访问 s[3] ,它应该发出'c'

s[3]'c'还是"c"

就像它是 char 数据类型还是字符串数据类型?

std::string 不是内置类型,因此 s[3] 中的运算符[]是对字符串模板中定义此运算符的成员函数的调用。

您可以通过查找operator []的参考页面来找到该类型:

返回对指定位置处字符的引用。

若要从文档中查找类型referenceconst_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;

s[3]是"C"还是"C"?

字符"c

",而不是字符串"c"。

最容易记住的是,std::string 不像 char 那样是本机类型,而是一个包装class,其中包含用于形成字符串的chars数组。

std::string只是重载 C 数组运算符 [] 以返回给定索引处的char,因此:

s[3]'c'还是"c"

答:'c'