Difference Between string and char[] Types in C++
Last Updated :
02 Feb, 2024
In C++, we can store the sequence of characters i.e. string in two ways: either as a std::string object or char array. In this article, we will discuss some major differences between string and char[] in C++
Character Array Type Strings
A character array is simply an array in C++ that contains characters that are terminated by a null character. Here, characters present in the character array can be accessed by the index of the array. These types of strings are inherited from the C language
Syntax
char str[14] = "GeeksforGeeks"
Example
C++
#include <iostream>
using namespace std;
int main()
{
char str[13] = "GeeskforGeeks" ;
for ( int i = 0; i < 11; i++) {
cout << str[i];
}
return 0;
}
|
std::string in C++
The std::string is a class that is used to represent strings in C++. They are the modern counterpart of old character array type strings. They contain many different functions to help in string manipulation.
Syntax
string str("GFG is best");
Example
C++
#include <iostream>
using namespace std;
int main()
{
string str( "GFG is best" );
cout << str;
return 0;
}
|
Difference between String and Char[] types in C++
The below table lists the major differences between the char[] type and std::string type strings in C++:
It does not contains ‘\0’ at the end. |
It contains ‘\0’ at the end. |
There is no need to worry about memory management |
If allocated on stack, the memory remains fixed. If allocated on heap, user have to manually manage the memory. |
Represented as the objects of std::string objects and are also implement internally using character arrays. |
Directly implemented and represented as character arrays. |
Have some associated function to help in string manipulation. |
No associated functions. String manipulation is done by using the explicitly defined functions in <string.h> header. |
It is defined in the <string> header in C++ |
It is the part of the language.
|
Only works in C++.
|
Works in both C and C++.
|
Share your thoughts in the comments
Please Login to comment...