A string object via string class can be initialized when you define it using
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
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:
The memory space required is adjusted automatically.
#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; }