In this mastery I will talk to you about a really simple topic, “Strings”.

Well, first of all strings are a one-dimensional array of characters which is terminated by a null character ‘’. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word “Hello”. To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Hello.”

char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};

 

If you follow the rule of array initialization, then you can write the above statement as follows:

char greeting[] = "Hello";

 

Following is the memory presentation of above defined string in C/C++:

string_representation

Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the ‘’ at the end of the string when it initializes the array. Let us try to print above-mentioned string:

#include <iostream>

using namespace std;

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''};

   cout << "Greeting message: ";
   cout << greeting << endl;

   return 0;
}

 

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

 

For any other doubt please feel free to write it in the comments.

Sources:

http://stackoverflow.com/questions/10219225/c-create-string-of-text-and-variables

http://www.cs.fsu.edu/~myers/c++/notes/stringobj.html

-The Admin

CC BY 4.0 Creation and use of Strings in C++ by esaupreciado is licensed under a Creative Commons Attribution 4.0 International License.