1.7.  Strings

[ fromfile: strings.xml id: stlstrings ]

When working with string data in C++, we have three choices.

  1. const char*, or c-style strings, which are used mainly when we are interfacing with C libraries, and rarely otherwise. They are an important source of runtime errors and should be avoided.

  2. string, from the C++ standard library, which is available everywhere.

  3. QString, which is preferred over STL strings, because it has a richer API and is easier to use. Its implementation supports lazy copy-on-write (which means functions can receive QString arguments and return QStrings by value without allocating and copying the entire string). ALso, QString has built-in support for the Unicode standard which facilitates internationalization.

Example 1.4 demonstrates basic usage of STL strings.

Example 1.4. src/generic/stlstringdemo.cpp

#include <string>
#include <iostream>

int main() {
    using namespace std;
    string s1("This "), s2("is a "), s3("string.");
    s1 += s2;  1
    string s4 = s1 + s3;
    cout << s4 << endl;

    string s5("The length of that string is: ");
    cout << s5 << s4.length() << " characters." << endl;

    cout << "Enter a sentence: " << endl;
    getline(cin, s2);  /*s2 will get the entire line.*/
    cout << "Here is your sentence: \n" << s2 << endl;
    cout << "The length of it was: " << s2.length() << endl;
    return 0;
}

1

concatenation

Here is the compile and run:

src/generic> g++ -Wall stlstringdemo.cpp 
src/generic> ./a.out
This is a string.
The length of that string is 17
Enter a sentence:
20 years hard labour
Here is your sentence:
20 years hard labour
The length of it was: 20
src/generic> 

Observe that we used

getline(cin, s2)

to extract a string from the standard input stream. The same example, rewritten to use Qt instead of STL, is shown in Example 1.5.

Example 1.5. src/early-examples/qstring/qstringdemo.cpp

#include <QString>
#include <QTextStream>

int main() {
    QTextStream cout(stdout);
    QTextStream cin(stdin);

    QString s1("This "), s2("is a "), s3("string.");
    s1 += s2;  
    QString s4 = s1 + s3;
    cout << s4 << endl;

    QString s5 = QString("The length of '%1' is: %2 characters.")
        .arg(s4).arg(s4.length()); 1
    cout << s5 << endl;

    cout << "Enter a sentence: " << endl;
    s2 = cin.readLine();  /*s2 will get the entire line.*/
    cout << "Here is your sentence: \n" << s2 << endl;
    cout << "The length of it was: " << s2.length() << endl;
    return 0;
}

1

Argument parametrization

Observe that, this time, we used

s2 = cin.readLine()

function to extract a QString from the standard input stream.