| Character Array | String Class |
|---|---|
| A character Array is an array used to store character-type data. Ex: char ch[4] = "abc"; |
A string is a class in C++ programming and the string type variable is
basically the object of the string class. Ex: string str = "algolesson"; |
| In character Array, we need to know the size of an array in advance. | It string there is no need to know the size in advance. They adjust their size based on the requirement. |
| We cannot use C++ Operator on Character Array. | We can use C++ Operator on String Class. |
| Operations like concatenation or append are difficult as a larger size Char array is required. | An operation like concatenation or append are easier change in string size takes place automatically. |
| Character Arrays are much faster. | Strings are slower as compared to the character array. |
//C++ example program for Character Array #include<iostream> #include<cctype> using namespace std; int main(){ char ch[]{"Algolesson"}; cout<<ch<<endl; ch[4] = 'L'; for(int i = 0; i < 11; i++){ cout<<ch[i]; } return 0; }
Algolesson AlgoLesson
The drawback of Character Array.
char ch1[]{"algolesson"}; //OK ch1 = "coding"; //error- not OK
char ch2[]{"welcome"};
ch2 = ch1 + ch2; //error - we cannot use operator
- Once the Character array is initialized with a set of characters then it cannot be initialized again with a different set of characters.
- We cannot use + operators on Character Arrays in C++.
//C++ example program for String Class #include<iostream> #include<string> using namespace std; int main(){ string str1 = "Welcome to "; string str2 = "Algolesson"; cout<<str1<<endl;
cout<<str2<<endl; cout<<"Size of str1: "<<str1.size()<<endl; str1 = str1 + str2; //concatenation cout<<str1<<endl; cout<<"Size of str1: "<<str1.size()<<endl; return 0; }
Welcome to
Algolesson
Size of str1: 11
Welcome to Algolesson
Size of str1: 21

.jpg)