Introduction:
The primary approach for handling strings in C++ is referred to as std::string, as it grants users access to a diverse array of beneficial features. In addition to various other string manipulations, std::string facilitates tasks like searching for substrings, comparing strings, combining strings, and extracting portions of strings. However, with each operation executed on the string, std::string mandates the dynamic allocation of extra memory along with supplementary buffer space.
Define string_view.
Stringview is limited to observing a string's content without the ability to modify it. Unlike duplicating a string, no actual data copying occurs during the creation of a stringview. Additionally, it consumes less heap memory compared to std::string. This feature is exclusive to C++ 17, and std::string_view does not allow alterations to the original data.
The compact std::stringview object points directly to the continuous character sequence, providing only read access to a string or a substring by mimicking the std::string interface. It presents a perspective of a string that originates from a different location in the source code, in contrast to std::string that holds an independent duplicate of the string.
It has two members:
Prepend the size and a const char* thacpp guides to the start of the character array. This points to a string that is not owned by anyone. This is detailed in the header (# include "stringview" ) and std::.
Why would we use std::string_view?
There are various reason that would requires the string_view. Some of them are as follows:
- When you wish to eliminate extra copies , string_view is helpful.
- Building and copying Stringviews requires less memory. Stringview doesn't need a dynamic allocation when it is created from literals.
- In the same way, std::string::substr returns a new string when producing a substring, which may need a dynamic allocation. In order to prevent any more memory from being dynamically allocated, we can create a string_view from the address of a specific location in our string.
Syntax
The subsequent syntax is employed to define a string_view object:
std::string_viewstr_view("Hello, world!");
By performing this action, the string "Hello, world!" is accessed through a string_view object.
Members
The following individuals create for the string_view class:
- data: A reference to the string's beginning.
- size: It is used to determine the string's width.
Methods
Below are the functions provided by the string_view class:
begin:
It provides a reference to the start of the string as a return value.
end:
It gives a pointer to the string's end.
length:
It gives the string's size back.
sizet start, sizet end, substr:
A fresh string_view object is generated, referencing a segment of the existing string.
compare(const std::string_view& other):
When compared to a different string_view object, the current string is evaluated.
equals(const std::string_view& other):
If the existing string matches another string_view object, it will result in a true value.
find(char c):
It returns the index of the first occurrence of the specified character within the string.
rfind(char c):
It provides the index of the last occurrence of the specified character within the string.
contains(char c):
If the specified character exists within the string, a boolean value of true is returned.
Why the use of std::string_view comes in actually:
Let's see why and how we are making use of std::string_view practically by taking some examples;
Constant strings are commonly encountered when working with std::string, highlighting a drawback of this data type. The following program demonstrates the challenges associated with utilizing std::string for managing constant strings:
//C++ program to display the issue with the string
#include <iostream>
#include <string>
using namespace std;
// Driver Code
int main()
{
char str_1[]{ "Hello !, JavaCppTutorial" };
string str_2{ str_1 };
string str_3{ str_2 };
// Printing the string
cout<< str_1 << '\n'
<< str_2 << '\n'
<< str_3 << '\n';
return 0;
}
Output:
Hello !, JavaCppTutorial
Hello !, JavaCppTutorial
Hello !, JavaCppTutorial
Explanation:
The outcomes align with the expected outcomes. Nevertheless, the std::string incurs memory overheads twice to showcase "Hello!, JavaCppTutorial" twice. In this scenario, the text ("Hello!, JavaCppTutorial") was only read; there was no requirement to write to it. Thus, why allocate memory repeatedly solely for displaying a string? C++17 introduced std::string_view, offering a perspective of a pre-existing char str without introducing a new object to memory, enabling more efficient string handling.
The problem with std::string
By defining two separate string variables, the same string, str1, is duplicated in the previous instance. Consequently, static memory allocation was employed for both variables str2 and str_3, resulting in a duplication of memory overhead.
Advantages of using std::string_view
There are multiple benefits of utilizing std::string_view. The primary advantages of this function include:
Cheaper and lighter:
The primary objective of the cost-effective std::stringview, which is lighter in weight, is to provide a glimpse of the string. Replicating the string in a less efficient manner, as demonstrated earlier, and incurring additional RAM overhead when creating the stringview is unnecessary. Any modifications made to the original string are promptly mirrored in the std::string_view, significantly enhancing the efficiency of the string duplication procedure.
Improved Efficiency:
The std::string_view outperforms the const std::string& by removing the necessity for a std::string object to start at the beginning of the string. It consists of two components - a const char* indicating the array's initial location and a size property.
Supports an important function
The majority of crucial functions carried out on a std::string, like substr, compare, find, and overloaded relational operators (such as ==, >, and !=), are also available in the std::string_view. Opting for read-only mode often eliminates the necessity for declaring a std::string object.
Here is the precise source code for the program mentioned earlier utilizing std::string_view:
//creating a C++ program to put the above strategy into practise
#include <iostream>
using namespace std;
#include <string_view>
// Driver code
int main()
{
// View the binary's "hello" text.
string_view str_1{ "Hello !, JavaCppTutorial" };
string_view str_2{ str_1 };
string_view str_3{ str_2 };
std::cout<< str_1 << '\n' << str_2 << '\n' << str_3 << '\n';
return 0;
}
Output:
Hello !, JavaCppTutorial
Hello !, JavaCppTutorial
Hello !, JavaCppTutorial
Explanation:
The result would be identical to that seen above, but no more copies of the string "Hello!, JavaCppTutorial" would be produced in memory.
The C++ program to demonstrate the Char Type is below:
#include <iostream>
#include <string_view>
int main() {
const char* str = "Hello, world!";
std::string_view view(str);
std::cout<<view.length() << std::endl;
std::cout<< view << std::endl;
return 0;
}
Output:
13
Hello, world!
Std::string_view Example:
The following illustration showcases the utilization of various functions that operate on strings in combination with std::string_view. These functions include str.compare, str.back, str.cend, and str.at.
#include <iostream>
#include <string_view>
int main() {
const char* str = "Hello, world!";
std::string_view view(str);
if (view == "Hello, world!") {
std::cout<< "The strings are equal." << std::endl;
} else {
std::cout<< "The strings are not equal." << std::endl;
}
char last_char = view.back();
std::cout<< "The last character of the string is " <<last_char<< std::endl;
const char* end_ptr = view.cend();
std::cout<< "The end pointer of the string is " <<end_ptr<< std::endl;
char character_at_index = view.at(5);
std::cout<< "The character at index 5 is " <<character_at_index<< std::endl;
return 0;
}
Output:
The strings are equal.
The last character of the string is !
The end pointer of the string is
The character at index 5 is ,