Difference between String and Character array in C++
The main difference between a string and a character array is that strings are immutable, while character arrays are not.
String |
Character Array |
---|---|
Strings define objects that can be represented as string streams. | The null character terminates a character array of characters. |
No Array decay occurs in strings as strings are represented as objects. |
The threat of is present in the case of the character array |
A string class provides numerous functions for manipulating strings. | Character arrays do not offer inbuilt functions to manipulate strings. |
Memory is allocated dynamically. | The size of the character array has to be allocated statically. |
Know more about the difference between strings and character arrays in C++
Strings in C++
C++ strings are sequences of characters stored in a char array. Strings are used to store words and text. They are also used to store data, such as numbers and other types of information. Strings in C++ can be defined either using the std::string class or the C-style character arrays.
1. C Style Strings
These strings are stored as the plain old array of characters terminated by a null character ‘\0’. They are the type of strings that C++ inherited from C language.
Syntax:
char str[] = "w3wiki";
Example:
C++
// C++ Program to demonstrate strings #include <iostream> using namespace std; int main() { char s[] = "w3wiki" ; cout << s << endl; return 0; } |
w3wiki
2. std::string Class
These are the new types of strings that are introduced in C++ as std::string class defined inside <string> header file. This provides many advantages over conventional C-style strings such as dynamic size, member functions, etc.
Syntax:
std::string str("w3wiki");
Example:
C++
// C++ program to create std::string objects #include <iostream> using namespace std; int main() { string str( "w3wiki" ); cout << str; return 0; } |
w3wiki
One more way we can make strings that have the same character repeating again and again.
Syntax:
std::string str(number,character);
Example:
C++
#include <iostream> using namespace std; int main() { string str(5, 'g' ); cout << str; return 0; } |
Output:
ggggg