Strings and Characters

Comparing, Searching, and Replacing Text

The two strings can be compared with the usual relational operators.

Performs character by character comparisons from left to right until a difference is discovered or until the end of the shorter string is reached.

#include <iostream>
#include <string>

int main()
{
    std::string first = "apple";
    std::string second = "apricot";

    if (first < second)
    {
        std::cout << first << " comes before " << second << '\n';
    }

    if (first != second)
    {
        std::cout << "The two strings are different\n";
    }

    return 0;
}

For example, apple is less than apricot because they are not equal in their third character. p has a lower value than r.

Equality demands the characters in each position of the strings to be equal and that the strings should be of the same length.

These operators therefore provide a consistent ordering that can be used for either sorting strings or making simple decisions.

Searching refers to finding some sequence of characters within a larger string.

The member function find() returns the position of the first element of the sequence requested.

If the sequence cannot be found, this function returns the special constant std::string::npos.

#include <iostream>
#include <string>

int main()
{
    std::string text = "the call stack grows";
    // Search the string and return the matching position
    std::string::size_type pos = text.find("stack");

    if (pos != std::string::npos)
    {
        std::cout << "Found at position " << pos << '\n';
    }
    else
    {
        std::cout << "Not found\n";
    }

    return 0;
}

Search searches the string starting at the beginning and moving forward until it finds the requested characters or has got to the end.

If the sequence is found, the value returned is the index of the first character in the sequence.

If there is no sequence, the program returns std::string::npos.

This value is guaranteed not to be a valid string position. It is therefore the reliable method of testing whether the search was successful by comparing the result with the position value, std::string::npos.

The position returned should not be used as an index until it has been compared with std::string::npos.

A beginning position may be supplied to find() so that it starts searching later in the string.

This feature works when we have repeated the same sequence multiple times.

The first call can find the first occurrence. A second call could start right where that one left off, and search for the second occurrence.

#include <iostream>
#include <string>

int main()
{
    std::string line = "one two one two";
    std::string::size_type first = line.find("one");
    std::string::size_type second = line.find("one", first + 1);

    std::cout << "First occurrence at " << first << '\n';
    std::cout << "Second occurrence at " << second << '\n';

    return 0;
}

If there is another one, its starting index is returned.

If there is no later occurrence, the function again returns std::string::npos.

Replacing: Deletes a series of characters and inserts a different series of characters in its place.

The member function replace() accepts an initial position, an amount of characters to be deleted, and an insertion string.

For instance, a replacement could start at position 0 in old, delete the first three characters, and insert new at position 0.

#include <iostream>
#include <string>

int main()
{
    std::string sentence = "the old frame";
    // Replace the selected range of characters
    sentence.replace(4, 3, "new");

    std::cout << sentence << '\n';

    return 0;
}

The string that is produced should contain the replacement text but keep the rest of the string unchanged.

The length of the string varies based on the adjustment between number of deletions and number of insertions.

The call to the starting index must be valid.

If the number of characters to remove exceeds the number of available characters in the string at this point, characters are removed from this point on and the new text is inserted.

If the string to be replaced is known by its content rather than by its position, then both find() and replace() can be used along with each other.

The search is initiated by passing in the sequence and the search method returns the position of the sequence.

The output is changed to check for std::string::npos accordingly.

If find() worked, you can then pass the position returned to replace().

#include <iostream>
#include <string>

int main()
{
    std::string phrase = "replace the word word";
    std::string::size_type loc = phrase.find("word");

    if (loc != std::string::npos)
    {
        phrase.replace(loc, 4, "term");
    }

    std::cout << phrase << '\n';

    return 0;
}

This overrules the first matching occurrence.

Only the occurrence is replaced. To replace all the occurrences, we need to again search and replace in a loop.

So searching, replacing, and comparing are all based on these three simple guarantees:

The relational operators offer a uniform character by character ordering.

find() yields an index value you can use or an obvious value which is std::string::npos.

The replace() uses a valid start position and will automatically adapt string characters and size.

Exercise: Comparing, Searching, and Replacing TextStarter code, hints and solutionOpenClose
Guided practiceBeginner · 10–15 min

Practice: Comparing, Searching, and Replacing Text

Work through the mission, reveal hints only when needed, and compare your result with the model solution.

Your challenge

Use apple as the new value of second and add a labeled equality check. Predict which existing comparison branches run; these test values are initializers, not console input.

Mission checklist

  1. Run the starter as a baseline, then predict the change requested in Your challenge.
  2. Make that change in your editor; use the lesson-specific hints if you need help.
  3. Compile and run your answer, then compare with the worked solution and explain the result.

Starter program

This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.

#include <iostream>
#include <string>

int main()
{
    std::string first = "apple";
    std::string second = "apricot";

    if (first < second)
    {
        std::cout << first << " comes before " << second << '\n';
    }

    if (first != second)
    {
        std::cout << "The two strings are different\n";
    }

    return 0;
}

Hints

Hint 1

Compare "apple" and "apricot" one character at a time until the first difference. String ordering is not a comparison of their lengths.

Hint 2

Set second equal to first to test equality. Both the < condition and the != condition should be reconsidered independently.

Worked solution

This starter has initialized strings rather than std::cin input. I use a new test value by changing second to apple. The added equality report prints 1; neither the less-than nor not-equal branch runs.

#include <iostream>
#include <string>

int main()
{
    std::string first = "apple";
    std::string second = "apple";

    if (first < second)
    {
        std::cout << first << " comes before " << second << '\n';
    }

    if (first != second)
    {
        std::cout << "The two strings are different\n";
    }

    std::cout << "Strings equal: " << (first == second) << '\n';
    return 0;
}

Example output

Strings equal: 1

0 comments

No comments yet. Be the first.

Add a comment

About CppLearn

CppLearn is an interactive, free reference for modern C++. In each lesson, you'll find out how the language works, rather than just lines of code that you can copy and paste. We cover concepts starting from beginner lessons on fundamentals and proceed to templates, move semantics, smart pointers, and areas that usually trap or scare C++ learners.