C++ Programming Series: Char, Char Arrays and Strings

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 is 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".

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 as 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 with 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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s