
C++ Strings
#include <iostream>
#include <string>
using namespace std;
main()
{
// Get some parts of speech, and combine them.
cout << "Proper Noun? ";
string res;
cin >> res;
cout << "Transitive Verb? ";
string s;
cin >> s;
res += " " + s + " the ";
cout << "Noun? ";
cin >> s;
res += s;
cout << "Adverb? ";
cin >> s;
res += " " + s + ".";
// Check this one.
if(s.substr(s.length() - 2, 2) != "ly")
cout << "Hmmm. Adverbs _usually_ end in \"ly.\"" << endl;
cout << "Useless sentence: " << res << endl;
int pos = res.find("q q");
if(pos != string::npos)
cout << "Wow! Your sentence contains q, space, q "
<< "in position " << pos << ".\n"
<< " How likely is that?" << endl;
}
The C++ string facility is very good. Later in the term, we will talk
about the rather quirky string facility of plain C, and discover that
C++ loads better.
The C++ string facility is reminiscent of Java's, but has many
differences. Some are:
- In C++, you say string, not String.
- C++ strings are C++ objects, not Java-style references.
Therefore, comparison using == and other relationals
really works, and assignment
with = makes a separate, independent copy, much like Java clone.
- In C++, strings not used so extensively for I/O purposes, mostly because
streams is quite powerful.
One other unfamiliar thing in the program is the name
string::npos. This is simply a named constant integer value declared
in the standard library's string class.
(It's probably -1, but I haven't tried to find out.)
As we will see much later when we get to classes,
C++ uses the :: notion to select members of a class, and reserves the dot
for members of an object. Java uses the dot for both purposes.
And one final warning: in Java, double-quoted constants are strings.
In C++, they are not. (As for what they are, and why, you must wait.)
In most cases, conversion to string is automatic, but if you
get mysterious errors, say string("whatever") to make
an explicit conversion.
Reading: pp. 49-53