C++ Strings

Strings are a set of characters.A string is also an array of characters.

  • The last character of every string is a null character that is represented by the ASCII code for 0 which is \0.(‘\0’).This is for the compiler to know where the string ends.

  • C++ does not regard a character array that does not end with a null character as a string.

Declaring a string

char mystring[11] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’};

  • This means if the string is declared by specifying each character, then the null character must be included in the string.Hence even if the length of the word is 10, the length of the string is 11 and the last or 11th character is nothing but the null character.

An alternative to declare a character array as a string is to initialise the character array with the characters  enclosed in double quotes without having to specify the null character. The compiler implicitly adds null character.

  • char mystring[4] = “Hey”; 

  • Note the length of the array. In this case it is 4. The last or fourth character is for the null character

  •  If you create an array that is larger than required for the string literal along with the null character, then C++ simply fills the remaining elements of the array with null characters.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: