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++ Program to show the use of character array type strings #include <iostream> using namespace std;
int main()
{ // Character array
char str[13] = "GeeskforGeeks" ;
// Print each character in the array
for ( int i = 0; i < 11; i++) {
cout << str[i];
}
return 0;
} |
GFG is best
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++ Program to show the use of std::string #include <iostream> using namespace std;
int main()
{ // Sample string
string str( "GFG is best" );
// Print the string
cout << str;
return 0;
} |
GFG is best
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++:
std::string in C++ | Character Array 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++. |