Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

string s;
cin>>s;

suppose s = "stackoverflow"

now if we access s[3], it should give out 'c'

will s[3] be 'c' or "c"?

as in will it be a char data type or string data type?

like image 418
Archit Singh Avatar asked Dec 03 '22 13:12

Archit Singh


2 Answers

std::string is not a built-in type, so operator [] in s[3] is a call to a member function defining this operator in the string template.

You can find the type by looking up the reference page for operator []:

Returns a reference to the character at specified location pos.

To look up the type reference and const_reference from the documentation see "member types" section of std::basic_string<CharT> template.

If you are looking for std::string of length 1 starting at location 3, use substr instead:

s.substr(3, 1); // This produces std::string containing "c"
like image 155
Sergey Kalinichenko Avatar answered Feb 27 '23 04:02

Sergey Kalinichenko


It returns reference to the character as the operator [] is overloaded for std::string

char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;

will s[3] be 'c' or "c"?

Character 'c', not string "c".

like image 35
Saurav Sahu Avatar answered Feb 27 '23 03:02

Saurav Sahu