Working with Strings

Working with Strings#

We can use the same ideas we say with vectors on strings.

Find and Replace#

string has find and replace member functions. Here’s an example of extracting the basename of a file from a path and then replacing the extension.

There are a lot of different ways we can do a replace: std::string::replace calls .

Listing 26 string_replace.cpp#
#include <iostream>
#include <string>

int main() {

    std::string filename{"~/classes/test.cpp"};
    std::cout << "filename: " << filename << std::endl;

    // let's find just the base file name -- reverse find for '/'

    auto ipos = filename.rfind('/');

    // create a substring containing just the base name
    // if we don't provide a length, substr goes to the end

    std::string basename = filename.substr(ipos+1);

    std::cout << "basename = " << basename << std::endl;

    // now let's change the extension from .cpp to .txt

    auto ipos_ext = basename.rfind('.');

    // there are many forms of replace -- here's well use iterators
    // that mark the start and end of the original string and those of
    // the string we want to substitute

    std::string new_ext = ".txt";

    basename.replace(basename.begin()+ipos_ext, basename.end(),
                     new_ext.begin(), new_ext.end());

    std::cout << "basename = " << basename << std::endl;

}

Tip

C++17 introduced the filesystem library that includes a stem function that can do this as well. We’ll look at the filesystem library later.

Other Functions#

There are a large number of member functions that work on strings. See for instance: https://www.cplusplus.com/reference/string/string/

try it…

Let’s try to use std::string::find_first_of, following this: https://www.cplusplus.com/reference/string/string/find_first_of/