Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Building a string
    4. Searching and cutting: find and substr
    5. Checking the start, the end and the middle
    6. Comparing and copying
    7. Short strings live inside the object
    8. std::string_view: text you only read
    9. A view looks at the string’s own characters
    10. String literals: ""s and ""sv
    11. Numbers to text and back
    12. std::from_chars: reading numbers you can’t trust
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. Adding two string literals
    17. A view of a string that’s gone
    18. std::stoi on text that isn’t a number
    19. Try it yourself

    Module 3 · Strings and containers

    3.1string and string_view

    Build, search, cut and compare text with std::string, see why short strings need no heap memory, read text without copying it through std::string_view, and turn numbers into text and back.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Building a string
    4. Searching and cutting: find and substr
    5. Checking the start, the end and the middle
    6. Comparing and copying
    7. Short strings live inside the object
    8. std::string_view: text you only read
    9. A view looks at the string’s own characters
    10. String literals: ""s and ""sv
    11. Numbers to text and back
    12. std::from_chars: reading numbers you can’t trust
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. Adding two string literals
    17. A view of a string that’s gone
    18. std::stoi on text that isn’t a number
    19. Try it yourself

    Key terms

    string literal
    Text in double quotes in your code, like "ACGT". Its type is an array of const char, not std::string.
    find and npos
    s.find(x) gives the position of the first x in s, counting from 0, or the special value std::string::npos if there isn't one.
    small-string optimization (SSO)
    Storing short text inside the string object itself, so it needs no heap block. How short depends on the standard library.
    std::string_view
    A read-only view of characters that live somewhere else: a pointer to the first one and a length. It owns nothing and copies nothing.
    dangling view
    A view whose characters no longer exist, because the string it looked at was destroyed or moved its text. Reading it is undefined behavior.
    ""s and ""sv
    Suffixes that make a string literal a std::string ("ACGT"s) or a std::string_view ("ACGT"sv). They need using namespace std::literals;.
    null terminator ('\0')
    The character with code 0, put after the last character so that C functions can find where text ends.
    std::from_chars
    Reads a number from a run of characters (from <charconv>). It reports bad input in its result instead of throwing.

    You’ve used std::string to hold text since Variables. This lesson shows what it can do: grow, search, cut and compare. It also shows how a string stores short and long text, and std::string_view, which lets a function read text without copying it.

    In 30 seconds

    • A std::string owns its characters. It grows with +=, searches with find, cuts with substr and compares with == and <.
    • Short text fits inside the string object itself (up to 15 characters with GCC’s standard library), so it needs no heap block.
    • std::string_view is a pointer and a length: a view of text that lives somewhere else. Take it as a parameter when a function only reads text.
    • A view doesn’t keep its text alive. A view of a string that’s gone dangles.

    Building a string

    A std::string (from <string>) holds any number of characters. += adds text or a single character to the end, + concatenates (joins) two pieces into a new string, and [] reads one character by its position, counting from 0.

    #include <print>
    #include <string>
    
    std::string read = "ACGT";
    read += "TTAG"; // add text to the end
    read += 'C';    // add one character
    std::string tagged = read + "_1";
    std::println("{} has {} letters", read, read.size());
    std::println("first {}, last {}", read[0], read[read.size() - 1]);
    std::println("{} {}", tagged, std::string{}.empty());

    Output

    ACGTTTAGC has 9 letters
    first A, last C
    ACGTTTAGC_1 true

    size() is the number of characters, and empty() is true when there are none. Text in double quotes, like "ACGT", is a string literal. It isn’t a std::string itself, but C++ converts it to one wherever a string is expected, as in read += "TTAG".

    Searching and cutting: find and substr

    s.find(x) looks for a character or a piece of text and gives the position where it first starts. If it isn’t there, you get std::string::npos, a special value that means “not found”. s.substr(pos, count) copies count characters starting at pos into a new string; leave out count to take everything to the end.

    A FASTA header line holds a sequence name, a space and a description. Split it at the space:

    #include <print>
    #include <string>
    
    std::string header = ">chr1 length=248956422";
    std::size_t space = header.find(' ');
    std::string name = header.substr(1, space - 1); // skip the >
    std::string rest = header.substr(space + 1);
    std::println("name: {}, rest: {}", name, rest);
    std::println("{}", header.find("chrX") == std::string::npos);

    Output

    name: chr1, rest: length=248956422
    true

    The space is at position 5, so the name is the 4 characters from position 1. Always compare the result of find with npos before you use it as a position. A substr that starts past the end of the string throws a std::out_of_range exception, like .at() in Arrays and span.

    Checking the start, the end and the middle

    For yes-or-no questions, three member functions say what you mean more directly than find:

    #include <print>
    #include <string>
    
    std::string file = "sample_01.fastq";
    std::println("{} {}", file.starts_with("sample"), file.ends_with(".fastq"));
    std::println("{} {}", file.contains("_01"), file.contains('x'));

    Output

    true true
    true false

    Modern C++New in C++20 and C++23

    starts_with and ends_with arrived in C++20, and contains in C++23. Older code writes s.find(x) != std::string::npos for contains, and compares a substr for the other two.

    Comparing and copying

    == compares the text, not where it’s stored: two strings with the same characters are equal. < compares in lexicographic order, like a dictionary: the first character that differs decides. Characters compare by their numeric codes, and every uppercase letter comes before every lowercase one.

    #include <print>
    #include <string>
    
    std::string a = "ACGT";
    std::string b = "ACGA";
    std::string zebra = "Zebra";
    std::string apple = "apple";
    std::println("{} {} {}", a == b, b < a, zebra < apple);

    Output

    false true true

    a and b first differ at position 3, where A comes before T, so b < a. Z has the code 90 and a the code 97, so "Zebra" sorts before "apple".

    Assigning one string to another copies every character, so the two can change separately. A range-based for with char& changes each character in place:

    #include <print>
    #include <string>
    
    std::string dna = "GATTACA";
    std::string rna = dna; // a copy with its own characters
    for (char& base : rna) {
        if (base == 'T') {
            base = 'U';
        }
    }
    std::println("{} -> {}", dna, rna);

    Output

    GATTACA -> GAUUACA

    Short strings live inside the object

    Stack, heap and lifetime showed that a std::string is a fixed-size object, 32 bytes on this platform, that owns its characters on the heap. For short text, it doesn’t need the heap at all. The object keeps a small buffer of its own, and text that fits goes there. This is called the small-string optimization, or SSO. With GCC’s standard library, the buffer holds 15 characters, and capacity() tells you how many characters fit before the string needs a new block:

    #include <print>
    #include <string>
    
    std::string empty;
    std::string codon = "ATG";
    std::string read = "ACGTACGTACGTACGTACGT"; // 20 letters
    std::println("sizeof: {} {} {}", sizeof(empty), sizeof(codon),
                 sizeof(read));
    std::println("capacity: {} {} {}", empty.capacity(), codon.capacity(),
                 read.capacity());

    Output

    sizeof: 32 32 32
    capacity: 15 15 20

    All three objects are 32 bytes. empty and codon have room for 15 characters inside themselves. read is too long for that, so it owns a heap block with room for its 20 letters. Under the hood shows both layouts.

    PerformanceShort strings are cheap

    Creating, copying and destroying a string that fits in the buffer never touches the heap. Programs that handle many short pieces of text, like codons, gene names or k-mers, get this for free. The limit belongs to the standard library, not to C++: other libraries pick other limits.

    std::string_view: text you only read

    A function that takes const std::string& avoids a copy when you pass it a std::string. But pass it a string literal and C++ first builds a temporary std::string from the literal, which can mean a heap block for long text. And a piece of a string has to become a new string, through substr, before you can pass it at all.

    std::string_view (from <string_view>) removes both costs. Like the std::span from Arrays and span, it’s a view: a pointer to the first character and a length. Making one copies no characters, and it can look at a std::string, a string literal or part of either.

    #include <print>
    #include <string>
    #include <string_view>
    
    int count_gc(std::string_view seq) {
        int gc = 0;
        for (char base : seq) {
            if (base == 'G' || base == 'C') {
                ++gc;
            }
        }
        return gc;
    }
    
    int main() {
        std::string read = "GATTACAGC";
        std::println("{} {}", count_gc(read), count_gc("GGCC"));
        std::string_view middle = std::string_view{read}.substr(2, 4);
        std::println("{} has {}", middle, count_gc(middle));
    }

    Output

    4 4
    TTAC has 1

    The same function counts a std::string, a literal and a view, with no copies. A view’s substr returns another view, so middle points into read’s characters without copying them. A view has most of the reading functions a string has: size, [], find, starts_with, ends_with and contains.

    A view looks at the string’s own characters

    Because a view points at the original characters, a change to the string shows through the view:

    #include <print>
    #include <string>
    #include <string_view>
    
    std::string path = "reads/sample_01.fastq";
    std::string_view name = std::string_view{path}.substr(6, 9);
    std::println("{} ({} of {} letters)", name, name.size(), path.size());
    path[0] = 'R';
    path[6] = 'S';
    std::println("{}", name);

    Output

    sample_01 (9 of 21 letters)
    Sample_01
    A view into part of a stringpath is a std::string on the stack whose data pointer points to a heap block holding reads/, sample_01, .fastq and a zero character: 21 letters. name is a std::string_view on the stack with two fields: data points at the s of sample_01 inside path's heap block, and size is 9. The view copies nothing.StackHeappath: std::stringdatasize21name: std::string_viewdatasize9path's charactersreads/sample_01.fastq\0
    A view into part of a string. path is a std::string on the stack whose data pointer points to a heap block holding reads/, sample_01, .fastq and a zero character: 21 letters. name is a std::string_view on the stack with two fields: data points at the s of sample_01 inside path's heap block, and size is 9. The view copies nothing.

    A view only reads. Changing a character through it doesn’t compile:

    #include <string_view>
    
    std::string_view name = "sample_01";
    name[0] = 'S';

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:9: error: assignment of read-only location ‘name.std::basic_string_view<char>::operator[](0)’
        4 | name[0] = 'S';

    When you need text of your own that you can change or keep, make a string from the view: std::string copy{name};.

    Key ideaA view is a borrowed look, not a copy

    A std::string_view owns nothing. The text it looks at must stay alive, and in place, for as long as you use the view. As a function parameter that’s automatic: the caller’s string outlives the call. A view is only a pointer and a length (16 bytes here), so pass it by value, not as const std::string_view&.

    String literals: ""s and ""sv

    A string literal on its own is an array of const char. Give it to auto and the array decays to a pointer, as in Arrays and span. The suffix s makes the literal a std::string, and sv makes it a std::string_view. Both need using namespace std::literals;, which brings in the standard library’s literal suffixes and nothing else.

    #include <print>
    #include <string>
    #include <string_view>
    
    using namespace std::literals;
    
    auto plain = "ACGT";  // const char*: a pointer to the A
    auto owned = "ACGT"s; // std::string
    auto view = "ACGT"sv; // std::string_view
    std::println("{} {} {}", sizeof(plain), sizeof(owned), sizeof(view));
    std::string joined = "ACGT"s + "TTAG";
    std::println("{}", joined);

    Output

    8 32 16
    ACGTTTAG

    Numbers to text and back

    std::to_string turns a number into a std::string. In C++23, for a double it always writes six decimal places (C++26 changes it to the shortest form); std::format, from Printing and reading, writes the shortest form already. In the other direction, std::stoi reads an int from the start of a string and stops at the first character that isn’t part of the number.

    #include <format>
    #include <print>
    #include <string>
    
    std::string label = "read_" + std::to_string(42);
    std::println("{}", label);
    std::println("{} {}", std::to_string(0.1), std::format("{}", 0.1));
    std::println("{} {}", std::stoi("250"), std::stoi("37bp"));

    Output

    read_42
    0.100000 0.1
    250 37

    std::stoi("37bp") quietly ignores the bp. If there’s no number at the start, it throws a std::invalid_argument exception, and if the number doesn’t fit in an int, a std::out_of_range. Either stops the program unless something catches it (Exceptions shows how).

    std::from_chars: reading numbers you can’t trust

    Text from a file or a user can be anything. std::from_chars (from <charconv>) reads a number from a run of characters, given as a pointer to the first one and a pointer just past the last. It never throws. Instead it returns a result with two fields: ec, an error code of type std::errc (from <system_error>) that equals std::errc{} when it worked, and ptr, which points just past the last character it used.

    #include <charconv>
    #include <print>
    #include <string_view>
    #include <system_error>
    #include <vector>
    
    std::vector<std::string_view> fields = {"1500", "12x", "abc",
                                            "99999999999"};
    for (std::string_view field : fields) {
        int value = 0;
        const char* end = field.data() + field.size();
        auto result = std::from_chars(field.data(), end, value);
        if (result.ec == std::errc::invalid_argument) {
            std::println("{}: not a number", field);
        } else if (result.ec == std::errc::result_out_of_range) {
            std::println("{}: too big for an int", field);
        } else if (result.ptr != end) {
            std::println("{}: {} then extra text", field, value);
        } else {
            std::println("{}: {}", field, value);
        }
    }

    Output

    1500: 1500
    12x: 12 then extra text
    abc: not a number
    99999999999: too big for an int

    field.data() is the pointer to a view’s first character. Checking result.ptr against end catches the 12x case that std::stoi lets through.

    Which one should I use?

    WhatWhenWhyHow
    std::stringYou keep text: store it, build it, change it or return it from a function.It owns its characters and frees them for you.std::string name = "chr1";
    std::string_view parameterA function only reads text while it runs.It accepts a std::string, a literal or part of either, and copies nothing.int count_gc(std::string_view seq)
    const std::string& parameterThe function passes the text on to code that needs a std::string, or a '\0' at the end.A view might not end in '\0', so it would need a copy first.void open_file(const std::string& path)
    std::from_charsTurning text from a file or a user into a number.It reports bad input and extra characters without throwing.std::from_chars(first, last, value)
    std::formatTurning numbers into text.It writes the shortest form of a double and lets you choose the layout.std::format("{:.2f}", score)

    Rule of thumb: store text in a std::string, read it through a std::string_view, and don’t keep a view longer than the string it looks at.

    Under the hood

    With GCC’s standard library, a std::string is a pointer to its characters, a length, and 16 more bytes. For long text, 8 of those bytes hold the capacity. For short text, all 16 are the buffer: up to 15 characters and the '\0' after them, with the pointer aimed at the buffer. A std::string_view is just a pointer and a length.

    std::string and std::string_view, with GCC's standard library
    std::string and std::string_view, with GCC's standard library: each row is one value; each cell's width is its size in bytes.
    Value012345678910111213141516171819202122232425262728293031Size
    long std::stringdata8 bytes · pointersize8 bytescapacity8 bytesunused8 bytes32 bytes
    std::string "ATG"data8 bytes · pointersize8 bytesATG\04 bytesrest of buffer12 bytes · unused32 bytes
    std::string_viewdata8 bytes · pointersize8 bytes16 bytes

    A long std::string is 32 bytes: an 8-byte pointer to its heap block, an 8-byte size, an 8-byte capacity and 8 unused bytes. A short std::string holding ATG is also 32 bytes: the 8-byte pointer, which points at byte 16 of the same object, the 8-byte size, then the letters A, T, G and a zero character, followed by 12 unused bytes of the buffer. A std::string_view is 16 bytes: an 8-byte pointer and an 8-byte size.

    Other standard libraries lay a string out differently. Clang’s libc++ packs it into 24 bytes and still fits 22 characters inside:

    #include <print>
    #include <string>
    
    std::string empty;
    std::println("{} {}", sizeof(empty), empty.capacity());

    Output

    24 22

    A std::string always keeps a '\0' after its last character, so c_str(), a pointer to its first character, can hand the text to C functions, which find the end by looking for that zero. A view has no such promise. A view of part of a string ends wherever its length says, and the next character in memory is usually not '\0'. std::strlen (from <cstring>) counts characters up to the first '\0':

    #include <cstring>
    #include <print>
    #include <string>
    #include <string_view>
    
    std::string path = "reads/sample_01.fastq";
    std::string_view name = std::string_view{path}.substr(6, 9);
    std::println("{} {}", std::strlen(path.c_str()), name.size());
    std::println("{}", std::strlen(name.data()));

    Output

    21 9
    15

    Counting from the view’s first character, the first '\0' is at the end of path, 15 characters later, not 9. That’s why a function that needs C-style text should take const std::string& and call c_str().

    Common pitfalls

    Adding two string literals

    + joins a std::string with a literal, but two literals are two arrays of const char, and C++ has no + for arrays:

    #include <string>
    
    std::string pair = "ACGT" + "TTAG";

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:3:27: error: invalid operands of types ‘const char [5]’ and ‘const char [5]’ to binary ‘operator+’
        3 | std::string pair = "ACGT" + "TTAG";
          |                    ~~~~~~ ^ ~~~~~~
          |                    |        |
          |                    |        const char [5]
          |                    const char [5]

    Make one side a std::string: std::string{"ACGT"} + "TTAG", or "ACGT"s + "TTAG" with using namespace std::literals;. Two literals next to each other with nothing between them, "ACGT" "TTAG", are also joined, by the compiler.

    A view of a string that’s gone

    A function that takes and returns a view is a good design, but if you call it with a temporary string, the result points into text that’s destroyed at the end of the line. Here read_line() returns a new std::string, first_word returns a view into it, and the string is freed before word is used:

    #include <print>
    #include <string>
    #include <string_view>
    
    std::string_view first_word(std::string_view line) {
        return line.substr(0, line.find(' '));
    }
    
    std::string read_line() {
        return "sample_07_reads.fastq 1500 reads";
    }
    
    int main() {
        std::string_view word = first_word(read_line());
        std::println("{}", word);
    }

    This fails when it runs

    ERROR: AddressSanitizer: heap-use-after-free on address 0x…
    READ of size 21 at 0x… thread T0
        #0 memcpy
           … 9 frames inside the standard library
        #10 main main.cpp:15
    
    0x… is located 0 bytes inside of 33-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete(void*, unsigned long)
           … 6 frames inside the standard library
        #7 main main.cpp:14
    
    previously allocated by thread T0 here:
        #0 operator new(unsigned long)
           … 7 frames inside the standard library
        #8 read_line[abi:cxx11]() main.cpp:10
        #9 main main.cpp:14
    
    SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:15 in main

    The fix is to keep the string in a variable, std::string line = read_line();, and take views of line. If you need the word to outlive the line, store it as a std::string.

    Undefined behaviorThe simple case doesn't always compile

    std::string_view v = read_line(); makes the same mistake in one step. Clang spots that one and, with warnings as errors, refuses to compile it; GCC compiles it, and AddressSanitizer catches it when it runs. Neither compiler warns about the first_word version above, so don’t count on a warning.

    std::stoi on text that isn’t a number

    std::stoi throws an exception when there’s no number at the start of the text, and an exception nothing catches ends the program:

    #include <print>
    #include <string>
    
    std::string depth_field = "N/A";
    int depth = std::stoi(depth_field);
    std::println("{}", depth);

    This fails when it runs

    terminate called after throwing an instance of 'std::invalid_argument'
      what():  stoi

    For text you don’t control, use std::from_chars and check its ec, as shown above.

    Try it yourself

    Try it yourself

    read_length should return the number after len= in a read header, or -1 if there’s no len= or no number after it. It finds len= already, but always returns 0 instead of the number. Finish it with substr and std::from_chars.

    #include <charconv>
    #include <print>
    #include <string_view>
    #include <system_error>
    
    int read_length(std::string_view header) {
        std::size_t at = header.find("len=");
        if (at == std::string_view::npos) {
            return -1;
        }
        return 0; // read the number after len= instead
    }
    
    int main() {
        std::println("{}", read_length("read_17 len=150"));
        std::println("{}", read_length("read_18 len=abc"));
        std::println("{}", read_length("read_19"));
    }

    Expected output

    150
    -1
    -1
    Show a hint

    header.substr(at + 4) is a view of the text after len=. Pass its data() and data() + size() to std::from_chars, and return -1 if result.ec isn't std::errc{}.

    Show a solution
    #include <charconv>
    #include <print>
    #include <string_view>
    #include <system_error>
    
    int read_length(std::string_view header) {
        std::size_t at = header.find("len=");
        if (at == std::string_view::npos) {
            return -1;
        }
        std::string_view digits = header.substr(at + 4);
        int length = 0;
        auto result =
            std::from_chars(digits.data(), digits.data() + digits.size(), length);
        if (result.ec != std::errc{}) {
            return -1;
        }
        return length;
    }
    
    int main() {
        std::println("{}", read_length("read_17 len=150"));
        std::println("{}", read_length("read_18 len=abc"));
        std::println("{}", read_length("read_19"));
    }

    find locates len=, and substr gives a view of the digits after it without copying. std::from_chars reads the number and sets ec instead of throwing, so the abc case becomes -1 instead of a crash. Because the parameter is a std::string_view, the function accepts string literals with no std::string built along the way.

    Saved in this browser only.