string_view
Overview
estd::string_view
is a lightweight alternative to estd::string
. It serves as a
non-owning, read-only view of a string. Unlike estd::string
, it does not manage the
underlying memory but instead provides a reference to an existing string. estd::string_view
is commonly used when you want to efficiently process and operate on strings without modifying
them. It also offers functions like begin()
, operator[]
, data()
, remove_prefix()
etc.
It also contains a special struct named as string_view_tokens
which works over tokens of a
string_view
with given a set of delimiters.
Usage
The usage constraints and guidelines apply for string_view
.
Usage guidance |
While using functions like |
Example
The below code shows how operator=()
assigns values to the string.
estd::string_view view;
estd::string_view view2("Hello");
view = view2;
ASSERT_EQ('H', view[0]);
ASSERT_EQ('e', view[1]);
ASSERT_EQ(5U, view.size());
The below code shows the swapping of two views.
estd::string_view view = estd::string_view("Hello");
estd::string_view view2 = estd::string_view("Jellow");
ASSERT_EQ('H', view[0]);
ASSERT_EQ('e', view[1]);
ASSERT_EQ(5U, view.size());
ASSERT_EQ('J', view2[0]);
ASSERT_EQ('e', view2[1]);
ASSERT_EQ(6U, view2.size());
view.swap(view2);
ASSERT_EQ('H', view2[0]);
ASSERT_EQ('e', view2[1]);
ASSERT_EQ(5U, view2.size());
ASSERT_EQ('J', view[0]);
ASSERT_EQ('e', view[1]);
ASSERT_EQ(6U, view.size());
The piece of code shows how the string_view
can be used for tokenization.
estd::string_view view = estd::string_view("Hello World how is it going?");
estd::string_view delims = estd::string_view(" ");
estd::string_view expected_tokens[]
= {estd::string_view("Hello"),
estd::string_view("World"),
estd::string_view("how"),
estd::string_view("is"),
estd::string_view("it"),
estd::string_view("going?")};
auto tokens = view.tokenize(delims);
auto it = tokens.begin();
ASSERT_EQ(*it, expected_tokens[0]);
++it;
ASSERT_EQ(*it, expected_tokens[1]);
++it;
ASSERT_EQ(*it, expected_tokens[2]);
++it;
ASSERT_EQ(*it, expected_tokens[3]);
++it;
ASSERT_EQ(*it, expected_tokens[4]);
++it;
ASSERT_EQ(*it, expected_tokens[5]);
++it;
ASSERT_TRUE(it == tokens.end());