As we know that char
is one of the primitive types whereas string
is not a primitive type. Let us reveal some more facts about the two.
char
is basically, a number like int
. But that for each particular number, a specific letter or symbol is selected in accordance with the ASCII table. You can convert a char
to an int
temporarily to have the output, a number which represents that character.
In the main method:
char letter = 'b'; //Remember to use single quotes for 'char'
cout << (int)letter << endl; //Converting 'char' to 'int' and then, outputting.
We can convert a type into the other type. Type conversions have many methods and are not an easy topic. We will discuss it in details later on.
In other words, we can increment char
to have the next letter. If we do letter++;
before outputting it in its original form, the character will be ‘c’.
Following is an array of characters:
char word = { 'H', 'e', 'l', 'l', 'o' };
//Size of a single 'char' is 1 byte. So, 'sizeof(word)' gives 5.
for(int i = 0; i < sizeof(word); i++)
cout << word[i] << endl;
The char
array is a special case. There can be a very easy implementation to char
arrays in order to use them just like the non-primitive type, string
.
char word = 'Hello'; //Just like 'string' accept for single quotes
cout << word << endl; //No looping, pretty straight! Prints "Hello".
A string is a group of char
and can be considered as an array of them. It has many features and so, is better than a regular array of char
. We will go deep into strings later on but for now, here’s the array of string
:
string word = "Hello";
cout << word << endl;
string sentence[] = { "Hello,", "this", "is", "a", "sentence." };
for(int i = 0; i < sizeof(sentence)/sizeof(string); i++)
cout << sentence[i] << " ";
The basic difference between a string
and a char
array is that string
contains a special character at the end of the array of characters, called the null terminating character which tells the compiler to end the string
and proceed. In the case of the string
called word
, it is present after the ‘o’ of ‘Hello’.
This is pretty much for now and it might help you in handling characters and strings in C++. There are many confusions between the two and is usually mismatched in both, theoretical and practical ways. Try to do calculations with char
, char
arrays and strings, and figure out better ways yourself!