Working with std::string and string_view
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Text is not a built-in type
C++ inherited C strings, which are arrays of characters ending in a zero byte. You can still meet them in old code, and string literals like "hello" are of that kind. For your own code, use std::string. It grows as needed, copies safely, and cleans up after itself.
#include <iostream>
#include <string>
int main() {
std::string first{"Ghulam"};
std::string last = "Murtaza";
std::string full = first + " " + last;
full += "!";
std::cout << full << "\n";
std::cout << "length: " << full.size() << "\n";
std::cout << "first char: " << full[0] << "\n";
std::cout << std::boolalpha << full.empty() << "\n"; // false
}
The + operator joins strings. One catch: at least one side of the plus must be a std::string. The expression "hello" + " world" tries to add two pointers and will not compile. std::string{"hello"} + " world" is fine.
Searching and slicing
The member function find returns the position of the first match, or the special value std::string::npos if there is none. Always compare against npos. Do not compare with -1 or test for truthiness; a match at position 0 is a valid result.
#include <iostream>
#include <string>
int main() {
std::string email{"asha@example.com"};
auto at = email.find('@');
if (at == std::string::npos) {
std::cout << "not an email\n";
return 1;
}
std::string user = email.substr(0, at); // start, length
std::string domain = email.substr(at + 1); // from here to the end
std::cout << user << " | " << domain << "\n"; // asha | example.com
}
substr(pos, count) copies part of the string. If pos is beyond the end it throws, so check first when the input is untrusted. Other handy members: replace, erase, insert, rfind, find_first_of, and since C++20, starts_with and ends_with.
std::string file{"report_2025.csv"};
if (file.ends_with(".csv")) {
std::cout << "spreadsheet data\n";
}
Comparing
Unlike C strings, std::string supports ==, < and friends, comparing the contents. The comparison is case sensitive and based on character codes, so "Zebra" sorts before "apple". For case-insensitive comparison, convert both sides to the same case first.
#include <algorithm>
#include <cctype>
std::string toLower(std::string s) { // by value: we want a copy to change
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
The unsigned char in the lambda is not a typo. The character functions have undefined behaviour for negative values, and plain char may be negative for non-English text. This is a small detail that bites people. Also note that this only handles single-byte characters. std::string stores bytes, not letters, so an emoji or an Urdu letter in UTF-8 takes several elements. For real Unicode work you need a library such as ICU.
Numbers and strings
Use std::to_string to turn a number into text, and std::stoi, std::stod and friends to go the other way. These throw exceptions on bad input.
#include <iostream>
#include <string>
int main() {
std::string text{"42abc"};
try {
std::size_t used{};
int n = std::stoi(text, &used);
std::cout << "parsed " << n << " from " << used << " characters\n"; // 42, 2
} catch (const std::invalid_argument&) {
std::cout << "no digits at all\n";
} catch (const std::out_of_range&) {
std::cout << "number too big\n";
}
std::cout << std::to_string(3.5) << "\n"; // 3.500000
}
Notice that stoi("42abc") succeeds and returns 42. If you need the whole string to be a number, check that used equals the string length. Also note that to_string(3.5) gives six decimal places. For formatted output, use std::format, which we meet in the modern C++ lesson.
std::string_view
A std::string_view (C++17) is a lightweight window onto characters owned by someone else. It stores a pointer and a length and copies nothing. It is ideal for function parameters that only read text.
#include <string_view>
bool isGreeting(std::string_view s) {
return s.starts_with("Hello") || s.starts_with("Salaam");
}
// works with literals, std::string, and substrings, with no copies
The danger is lifetime. A view does not keep the text alive. Returning a string_view that points into a local std::string gives you a dangling view, exactly like a dangling pointer. Use views for parameters, and store a real std::string when you need to keep the text.
The common mistake
Adding two string literals, and comparing the result of find with the wrong value. Also common: passing const char* that is null into a std::string constructor, which is undefined behaviour. And storing a string_view of a temporary string, which dies at the end of the statement.
Try it yourself
- Write a function that takes a full name like "Ada Lovelace" and returns "Lovelace, Ada".
- Write
bool isPalindrome(std::string_view s)that ignores case and spaces. - Parse the line
"width=80"into a key and an integer value usingfind,substrandstoi.
#include <iostream>
#include <string>
int main() {
std::string first{"Ghulam"};
std::string last = "Murtaza";
std::string full = first + " " + last;
full += "!";
std::cout << full << "\n";
std::cout << "length: " << full.size() << "\n";
std::cout << "first char: " << full[0] << "\n";
std::cout << std::boolalpha << full.empty() << "\n"; // false
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account