Monday, April 18, 2011

STL string example in C++

Here's some STL string example code. STL string class is much more convenient compared to old character pointer(or array) string.However, it has its own weakness; the slower performance. So, you should use STL string carefully. (STL string example)



Sample 1 - setup for STL string

// 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";

// 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;
}