Search

10 Examples of using string_view in C++

And 2 more code examples ready as implementation.


10 Examples of using string_view in C++


std::string_view is a class named basic_string_view that uses char and std::char_traits , both as a template.

It is only available from C++17 and needs to include the string_view header. Can be implemented also for accented letters(std::wstring_view), unicode 8(std::u8string_view), 16(std::u16string_view, C++20) and 32(std::u32string_view ) .

It pretty much creates an array of characters for a string.

Each character is an index:

T e r m i n a l   R o o t
0 1 2 3 4 5 6 7 8 9 10 11 12

It is widely used in code that parses.

Let’s see 10 examples of using it!


01. Basic usage, declaring, initializing and printing a string_view

std::string_view sv {"Terminal Root"};
std::cout << sv << '\n';

02. Print only the 4th (fourth character)

std::cout << sv[3] << '\n'; // m


03. Get the size of the string_view

std::cout << sv.size() << '\n'; // 13

#04. Print the last character

std::cout << sv.back() << '\n'; // t

05. Know the position of the character 'i'

std::cout << sv.find("i") << '\n'; // 4

#06. Knowing the back to front position

std::cout << sv.rfind("o") << '\n'; // 11

It would be the 1st ‘o’ backwards, the find() would be 10 . Another note is if you enter a character that doesn’t exist, it will give garbage(string::npos, a weird number).

07. Check for 'X' character

std::cout << sv.find("X") << '\n'; // garbage

08. Print 9th to 13th character

std::cout << sv.substr(9, 13) << '\n'; // root

09. Remove the last 4 characters

sv.remove_suffix(4);
std::cout << sv << '\n'; // Terminal

#10. Remove the first 8 characters

sv.remove_prefix(8);
std::cout << sv << '\n'; // 'Root'


bonus

You can also use string_view_literals by adding the term sv to the end, example code with literal:

#include <iostream>
#include <string_view>

using namespace std::string_view_literals;

int main(){
  auto literal = "Terminal Root"sv;
  std::cout << literal << '\n';
  return 0;
}

Example of a ready code:

#include <iostream>
#include <string_view>
 
int main() {
    constexpr std::string_view unicode[] {
        "▀▄─", "▄▀─", "▀─▄", "▄─▀"
    };
 
    for (int y{}, p{}; y != 6; ++y, p = ((p + 1) % 4)) {
        for (int x{}; x != 16; ++x)
            std::cout << unicode[p];
        std::cout << '\n';
    }
}

Saída:

▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─
▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─
▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄
▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀
▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─
▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─

Some other functions are only available in C++20 or C++23, examples: contains(), starts_with() and others.

For more information visit: https://en.cppreference.com/w/cpp/string/basic_string_view .


cpp cppdaily


Share



Comments