Sample 1 - setup for STL string
// Headers.
//
#include <string>
#include <iostream>
// STL classes are defined in "std" namespace.
//
using namespace std;
int main(void)
{
// Create a string variable with name "str". The storage for "hello" is automatically
// managed by the string class.
//
string str = "hello";
// output to console.
// "hello" will be displayed.
//
cout << str << endl;
return 0;
}
Sample 2. String copy.
// Headers.
//
#include <string> // for STL string.
#include <iostream> // for cout.
// STL classes are defined in "std" namespace.
//
using namespace std;
int main(void)
{
// Create a string variable with name "str".
string str = "hello";
// Create a new string variable with name "str2" copying the content of "str".
string str2 = str;
// output to console.
// will display "hello".
//
cout << str2 << endl;
return 0;
}
Sample 3. String concatenation.
// Headers.
//
#include <string> // for STL string.
#include <iostream> // for cout.
// STL classes are defined in "std" namespace.
//
using namespace std;
int main(void)
{
// Create a string variable with name "str". The storage for "hello" is automatically
// managed by the string class.
//
string str = "hello";
// append another string " world" to the end of "hello".
//
str += " " + "world";
// output to console.
// will display "hello world".
//
cout << str << endl;
return 0;
}
Note - this kind of string contenation can cause performance degradation since it involves several memory allocations and copys.
Sample 4 - "char *" string and "string" string.
// Headers.
//
#include <string> // for STL string.
#include <iostream> // for cout.
// STL classes are defined in "std" namespace.
//
using namespace std;
int main(void)
{
// Old C style string.
char *oldStr = "hello";
// You can create new string variable from old C style string constant.
string str = string(oldStr);
// append another string " world" to the end of "hello".
//
str += " world";
// output to console.
//
cout << str << endl;
return 0;
}