Datasheet

// stringtest.cpp
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string myString = “Hello, World”;
cout << “The value of myString is “ << myString << endl;
return 0;
}
The magic of C++ strings is that you can use standard operators to work with them. Instead of using a
function, like
strcat() in C to concatenate two strings, you can simply use +. If you’ve ever tried to use
the
== operator to compare two C-style strings, you’ve discovered that it doesn’t work. == when used on
C-style strings is actually comparing the address of the character arrays, not their contents. With C++
strings,
== actually compares two strings. The example that follows shows some of the standard opera-
tors in use with C++ strings.
// stringtest2.cpp
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string str1 = “Hello”;
string str2 = “World”;
string str3 = str1 + “ “ + str2;
cout << “str1 is “ << str1 << endl;
cout << “str2 is “ << str2 << endl;
cout << “str3 is “ << str3 << endl;
if (str3 == “Hello World”) {
cout << “str3 is what it should be.” << endl;
} else {
cout << “Hmmm . . . str3 isn’t what it should be.” << endl;
}
return (0);
}
The preceding examples show just a few of the many features of C++ strings. Chapter 13 goes into fur-
ther detail.
22
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 22