Creating and initializing C++ strings

Creating and initializing strings is a straightforward proposition, and fairly flexible as well. In the example shown below :
the first string, blankString, is declared but contains no initial value. Unlike a C char array, which would contain a random and meaningless bit pattern until initialization, imBlank does contain meaningful information. This string object has been initialized to hold “no characters,” and can properly report its 0 length and absence of data elements through the use of class member functions.
The next string, secondString, is initialized by the literal argument “this is second string”. This form of initialization uses a quoted character array as a parameter to the string constructor
thirdString is simply initialized with an assignment.
fourthString, is initialized using an existing C++ string object. Put another way, this example illustrates that string objects let you:
1.Create an empty string and defer initializing it with character data
2.Initialize a string by passing a literal, quoted character array as an argument to the constructor
3.Initialize a string using ‘=‘
4.Use one string to initialize another


#include <string>
#include <iostream>
using namespace std;
int main() 
    // A blank string
    string blankString;
    // another way of initializing string
    string secondString("this is second string");
    // example of multiline string
    string thirdString = "this is multiline string "
    "and this is third one";
    // declaring while copying strings
    string fourthString(secondString);
    // A way to initialize string of size 20 with all 'A' characters
    string fifthString(30,'A');

    cout << "blankString = " << blankString << endl;
    cout << "secondString = " << secondString << endl;
    cout << "thirdString = " << thirdString << endl;
    cout << "fourthString = " << fourthString << endl;
    cout << "fifthString = " << fifthString << endl;
    return 0;

You may also like...