Cpp - String String Initializing

Introduction

A string object via string class can be initialized when you define it using

  • a predefined string constant
  • a certain number of characters
  • a predefined string or part of a string.

If a string is not initialized explicitly, an empty string with a length of 0 is created.

The length of a string, number of characters in the string, can be accessed using the length() method or its equivalent size().

string message("Good morning!"); 
cout << message.length();   // Output: 13 

String Assignments

When you assign a value to a string, the current contents are replaced by a new character sequence.

You can assign the following to a string object:

  • another string
  • a string constant or
  • a single character.

The memory space required is adjusted automatically.

Demo

#include <iostream> 
#include <string> 
using namespace std; 
string prompt("Enter a line of text: "),    // Global 
         line( 50, '*');                      // strings 
int main() //from  w ww .j av  a2  s. c  o m
{ 
    string text;                      // Empty string 
    cout << line << endl << prompt << endl; 
    getline( cin, text);        // Reads a line of text 
    cout << line << endl 
           << "Your text is " << text.size() 
           << " characters long!" << endl; 
                                            // Two new strings: 
    string copy(text),            // a copy and the 
           start(text,0,10);      // first 10 characters 
                                            // starting with 
                                            // position 0. 
    cout << "Your text:\n" << copy << endl; 
    text = "1234567890";          // Assignment 
    cout << line << endl 
           << "The first 10 characters:\n" << start << endl 
           << text << endl; 
    return 0; 
}

Result