
The string is a fundamental data type in many programming languages.1 In C++, a string is a data type that can store a sequence of characters. Despite being so ubiquitous and fundamental, strings are not primitive data types. To use a string in C++, you must include the <string> header from the standard template library (STL).
Strings as we know them are typically defined as “objects that represent sequences of characters.”2 The std::string that C++ developers are so familiar with is actually a specialization of the STL’s std::basic_string. In the STL’s string header, string is actually a type alias defined as such:
...using string = basic_string<char>;
So, what’s a basic_string? In short, this is just a class that generalizes the concept of a string; at their core, strings are just sequential collections of character-like objects. In our case, the std::string is just a sequential collection of objects with type char.
Now that we’ve gotten the definition of a string established, let’s briefly explore some of the properties of strings, namely the most commonly used string operators and methods.
Properties of Strings
Let’s create a simple string and try to print it to stdout:
<iostream> <string>int main() { // Create a string std::string hello = "Hello, world!"; std::cout << hello; return 0;}
Let’s compile and run this to see what we get:
❯ g++ printing_strings.cpp❯ ./a.outHello, world!
We see the text that we stored in the string printed to the terminal, just as we should expect.
Substrings and Indexing
Let’s look at an interesting property of strings: we can index into them to retrieve individual characters and even substrings!
<iostream> <string>int main() { // Create a string std::string index_me = "Hello, world!"; std::cout << index_me[4]; return 0;}
Remember, a string is really just an array of characters, so we can index into it like in the above example to retrieve the character at the specified index. When running the code above, we should expect to see the character at index 4, which is the letter ‘o’, printed to the terminal. Let’s see if that is the case.
❯ g++ string_indexing.cpp❯ ./a.outo
Lo and behold, we see the letter ‘o’ printed to the terminal just as we would expect. If we wanted to grab a substring, we can use the built-in substr method.
<iostream> <string>int main() { // Create a string std::string slice_me = "Hello, world!"; std::cout << slice_me.substr(7, 5); return 0;}
The substr method takes two parameters: pos and len, where pos is the starting array index position, and len is the number of characters to retrieve beginning with the character at pos.3 In the above code, we are taking a substring starting at index 7 (which is the letter ‘w’) and taking a total of 5 characters, including the character at index 7. This means that we should see ‘world’ printed to the terminal if we compile and execute the above code.
❯ g++ substrings.cpp❯ ./a.outworld
Concatenation
Strings can also undergo an operation known as concatenation. Concatenation is when multiple strings are chained together to create one larger string. In C++, concatenation can be accomplished using the + operator. Let’s look at an example.
<iostream> <string>int main() { // Create a couple strings std::string str1 = "Hel"; std::string str2 = "lo, wo"; std::string str3 = "rld!"; // Create a new string by concatenation of the previous strings std::string full_string = str1 + str2 + str3; // Verify the new string std::cout << full_string; return 0;}
We define three strings, and then we initialize another string by assigning it the result of the concatenation of the previous strings.
❯ g++ concat.cpp❯ ./a.outHello, world!
Strings can also be concatenated via the append method:
<iostream> <string>int main() { // Create a couple strings std::string str1 = "Hello, "; std::string str2 = "world!"; str1.append(str2); std::cout << full_string; return 0;}
❯ g++ concat.cpp❯ ./a.outHello, world!
Size
Another interesting property of strings is that we can query information about their size. In fact, strings in C++ possess some methods similar to those of std::vector. Let’s look at some of the methods available for gathering information about the size of a string:
<iostream> <string>int main() { // Create a string std::string example = "Let's use a different example"; // Query size and length, which are synonymous for strings std::cout << "Size of string: " << example.size() << "\n"; std::cout << "Length of string: " << example.length() << "\n"; // Check if string is empty std::cout << "String is empty: " << std::boolalpha << example.empty(); return 0;}
The size and length methods are synonymous, meaning we should see the same result for both. There is also the empty method which checks if the string is empty and returns a bool. If we compile and run, we should see that the size and the length of the string is 29 (because there are 29 characters in the string) and we should also see that the string is not empty (i.e., we should see false).
❯ g++ string_size.cpp❯ ./a.outSize of string: 29Length of string: 29String is empty: false
And that is exactly what we see!
Conclusion
These are just some of the basics for C++ strings. I am currently working on populating a new catalogue of C++ reference material under The Codex tab. I will post more information about strings including all the member methods and some advanced functionality, and when that page is available, I will provide a direct link here.
If you enjoy this type of content and want to stay in the know when I post new stuff, use the dialog below this post to subscribe to stay informed.