Tutorials / C++: From Basics to Modern C++ / Working with std::string and string_view

Working with std::string and string_view

14 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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

  1. Write a function that takes a full name like "Ada Lovelace" and returns "Lovelace, Ada".
  2. Write bool isPalindrome(std::string_view s) that ignores case and spaces.
  3. Parse the line "width=80" into a key and an integer value using find, substr and stoi.
cpp
#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