Contents



Introduction

C++ offers support for strings (std::string) as part of its standard library. However, it should not be mistaken with cstring (string.h).

Handling strings and working with them is easy and straight forward as long as we limit ourselves to ASCII characters. UTF-8 should not be much of an issue as well however there are some issues that may occur. UTF-16 and UTF-32 might be a bit trickier especially if the source is aimed to be deployed on different platforms and operating systems.

Creating Strings

#include <string>

std::string string_0 = "Hello, ";
std::string string_1 = "World!";

In order to access a “C style string” (array of chars) we can call the .c_str() member function.

In case we want to convert e.g. an integer to a string we could use std::to_string:

int a = 5;
std::string five_as_str = std::to_string(a);

Concatenating Strings

”+” Operator

The perhaps most common approach to concatenate strings in C++ is to use the addition operator (+):

std::string string_2 = string_0 + string_1

string_0 += string_1 // modifies string_0

The + operator can be using within the std::string Constructor as well:

std::string string_2 (string_0 + string_1);

Whatever we add could be a literal as well and does not need to be an initialized string.

Append

std::string string_2 = string_0.append(string_1);

C Style

Since basically all tutorials and guidelines on string concatenation for C++ somehow include a C example it might be wise to point a few things as most guidelines offer the perfect basis to shoot oneself into a foot. C and C++ are very different languages. It certainly is no longer “C with classes”. However, sometimes good old “C style” string handling is required to e.g. reduce memory footprint. The methods above are straight forward and hardly contain any mistake. However, strcpy is usually not explained properly and if possible strlcpy should be used anyhow. A fundamental issue with most examples covering strcpy that it assumes that the target buffer is large enough and no buffer overflow could occur. Another C style approach would be using strcat or strlcat. However, programming guard rails to avoid any buffer overflow is tricky and should be done by professions only - therefore use std::string ;).

Unless you really know what you are doing: Don’t use C Style strings with C++

Substrings

Check If String Contains Substring

Sometimes we want to know if a certain string contains a certain substring. The member function find takes care of that:

std::string string_0 = "some_tests";


if (string_0.find("test") != std::string::npos) {
    std::cout << "string_0 contains \"test\"" << std::endl;
} else {
    std::cout << "string_0 does not contain \"test\"" << std::endl;
}

If find returns std::string::npos, then no string was found.

Notes

Other C++ string related things might follow