Skip to content

Inspect and Change Text

The Course
•
35 min study

The planner will accept task titles of 1 through 40 characters. To enforce that rule, a program must look inside text: how long is it, is it empty, where is the first space? A std::string answers these questions because it is a sequence of characters, much like a vector of characters with extra text tools. The same rules about size and indexes apply, including the dangerous one: reading a position that does not exist is undefined behavior.

A string has size(), empty() and indexed characters. title[0] is the first character and title[title.size() - 1] is the last. A single character has the type char and is written in single quotes, such as 'r'. Text in double quotes, such as "r", is a string literal even when it holds one character. The two are not interchangeable: title[0] = "r"; is a compile error.

Predict and run

Predict before running C++
#include <iostream>
#include <string>

int main() {
    std::string title = "Read";
    if (!title.empty()) {
        title[0] = 'r';
    }
    title += " C++";
    std::cout << title << " " << title.size() << "\n";
    return 0;
}
Check your prediction
Text
read C++ 8

Assigning to title[0] changed the string in place. += then appended four characters, and the space counts as one of them, so the size is 8. Start with an empty title and keep the guard: the character assignment is skipped, the append still works, and the size is 4.

Why the guard matters

An empty string has size 0, so it has no character at index 0. Without the guard, title[0] = 'r'; on an empty string writes to a position that does not belong to any character you own. That is undefined behavior: it might appear to work, it might corrupt nearby data, and it gives no error message either way. Indexes must be less than size(), and checking empty() first is the simplest way to guarantee that for the first character.

The same goes for the last character. title[title.size() - 1] is safe only when the string is not empty, because on an empty string size() - 1 is computed with unsigned arithmetic and becomes an enormous number instead of -1.

Search with find

find looks for a character or a piece of text and returns the index where it starts. When there is no match, it returns the special value std::string::npos, which means "no position." Always compare with npos before using the result as an index.

Find a word boundary C++
#include <iostream>
#include <string>

int main() {
    std::string title = "Read chapter";
    std::size_t space = title.find(' ');
    if (space != std::string::npos) {
        std::cout << "First word: " << title.substr(0, space) << "\n";
        std::cout << "Space at: " << space << "\n";
    }
    std::cout << (title.find('x') == std::string::npos) << "\n";
    return 0;
}
Text
First word: Read
Space at: 4
1

substr(0, space) copies the characters from index 0, taking space of them, into a new string. The space itself sits at index 4, because counting starts at 0. There is no x in the title, so find returned npos and the comparison printed 1. The planner's helper uses the related functions find_first_of and find_first_not_of in the same way to check for line breaks and for titles made only of spaces.

Bytes, not letters

size() counts the bytes the string stores. For plain English letters, digits and punctuation, called ASCII, one character is one byte, so the count matches what you see. Many other characters, such as accented letters or emoji, take several bytes each, so size() can be larger than the number of visible characters. This course restricts titles to ASCII text so that "40 characters" and "40 bytes" mean the same thing.

Strings are values

Like a vector, a std::string owns its characters. Copying a string copies the text, so std::string backup = title; followed by title += "!"; leaves backup unchanged. When a string goes out of scope, it releases its memory automatically. You can build, grow and copy strings freely without ever managing memory yourself.

Practice

Exercise

Your turn

Given std::string title = "Read chapter";, print exactly:

  • First: R
  • Last: r
  • Size: 12
  • Has space: 1

If the title is empty, print only Empty title instead. Change the title to "" and then to "Review" and predict the output before each run.

Your workspace C++
#include <iostream>
#include <string>

int main() {
    std::string title = "Read chapter";
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Every indexed read needs a non-empty string, so put the empty case first and the four lines in the else branch.

Hint 2: a first step

Write the if (title.empty()) branch that prints Empty title, and in the else print only the First: and Size: lines. Run it with all three titles before you work out the last-character index and the space test.

Show one solution
Run the solution C++
#include <iostream>
#include <string>

int main() {
    std::string title = "Read chapter";
    if (title.empty()) {
        std::cout << "Empty title\n";
    } else {
        std::cout << "First: " << title[0] << "\n";
        std::cout << "Last: " << title[title.size() - 1] << "\n";
        std::cout << "Size: " << title.size() << "\n";
        std::cout << "Has space: " << (title.find(' ') != std::string::npos) << "\n";
    }
    return 0;
}
Text
First: R
Last: r
Size: 12
Has space: 1

The empty check comes first, so no index is ever used on a string without characters. For "Review" the output is First: R, Last: w, Size: 6 and Has space: 0, and the space test needed parentheses because it is a comparison inside an output chain. In the next lesson you will move collection code like this into functions, and pass the collection without copying it.

Was this article helpful?

Your response is saved on this device.