Strings

Strings#

reading

std::string on cplusplus.com

std::string#

A C++ std::string holds a sequence of characters. When working with strings, we include the <string> header.

Note

In C++, single characters (char) are enclosed in single-quotes, e.g., 'A', while strings are enclosed in double quotes, e.g. "string".

Warning

C++ can also use older C-style strings, which are essentially a null-terminated array of characters, e.g.,

char c_string[] = "this is my string";

These are quite inflexible and can lead to coding errors if you are not careful, and we will avoid them as much as possible.

Here’s a first example. We’ll create a string and we’ll concatenate another string onto it using the + operator:

Listing 14 string_example.cpp#
#include <iostream>
#include <string>

int main() {

    std::string example{"This is PHY 504"};
    std::cout << "original string: " << std::endl;
    std::cout << std::endl;

    example += ":\n Computational Methods in Physics and Astrophysics I\n";
    example += "Spring 2022";

    std::cout << example << std::endl;
}

In this example, the strings that we add to our initial string are actually C-style strings, but std::string knows how to work with them.

Note

We used an escape sequence here, \n, to create a newline. \n is slightly different than std::endl—the latter also flushes the output buffer.

We can use a constructor to create an initial string filled with a character repeated many times. For instance, here’s an 80-character line:

Listing 15 string-repeat.cpp#
#include <iostream>
#include <string>

int main() {

    std::string line(80, '-');

    std::cout << line << std::endl;

}

Here, '-' is a char and not a string.

Note

A nice overview of working with C++ strings is provided by “hacking C++”: std::string

String math#

There are a lot of operators and functions that can work on strings. See https://en.cppreference.com/w/cpp/string/basic_string.html

We can concatenate strings using the + operator:

Listing 16 string-cat.cpp#
#include <iostream>
#include <string>

int main() {

    std::string a{"this is a test"};
    std::string b{"of concatenation"};

    std::cout << a + " " + b << std::endl;

}