String Data Type In C++

Card image cap

String Data Type ?

C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string. String class stores the characters as a sequence of bytes with a functionality of allowing access to single byte character.


C++ string class internally uses char array to store character but all memory management, allocation and null termination is handled by string class itself that is why it is easy to use

The length of c++ string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string class is a container class, we can iterate over all its characters using an iterator similar to other containers like vector, set and maps, but generally we use a simple for loop for iterating over the characters and index them using [] operator.


Card image cap

Example 1:



Input :

aimtocode

Output :

The initial string is : aimtocode
The string after push_back operation is : aimtocode
The string after pop_back operation is : aimtocode
Card image cap

Example 2:



Output :

The new copied character array is : aimtocode

The 1st string before swapping is : aimtocodeer is for Prayag
The 2nd string before swapping is : aimtocode rocks
The 1st string after swapping is : aimtocode rocks
The 2nd string after swapping is : aimtocodeer is for Prayag
Card image cap