#include #include #include #include using namespace std ; //Problem when std::string is passed void print_view_char_array( const char* ptr ) { //need to recalculate string length std::cout << ptr << " (Length: " << strlen( ptr ) << ")\n"; } //New memory allocation if c style string is passed void print_view_standard_string( const std::string& str ) { std::cout << str << " (Length: " << str.length() << ")\n"; } // Best Practice: Pass by value, not by reference //Can take both c style and std::string without any new //memory allocation void print_view(std::string_view sv) { std::cout << sv << " (Length: " << sv.length() << ")\n"; } int main() { std::string str = "Modern C++"; //pass std string to old style c string. print_view_char_array ( str.c_str() ) ; //c style to std string& //new memory is allocated on the heap for the string print_view_standard_string( "Hello World!" ) ; // 1. Implicit conversion from literal (Zero allocation) print_view("Hello World") ; // 2. Implicit conversion from std::string (Zero allocation) print_view(str); // 3. Cheap substringing std::string_view full_view{"Data Science"}; std::string_view sub_view = full_view.substr(0, 4); // "Data" print_view(sub_view); cout << "full_view[0]" << full_view[0] << endl ; //No bounds checking but undefined behaviour //With g++ program aborts //cout << "full_view[20]" << full_view[20] << endl ; try { cout << "full_view.at(20)" << full_view.at(20) << endl ; } catch( out_of_range& obj1 ) { cout << "Exception." << obj1.what() << endl ; } cout << "full_view.back(): " << full_view.back() << endl ; //Not guranteed to be null terminated. string_view always keeps the //size information. cout << "full_view.data(): " << full_view.data() << endl ; //begin() end() cout << "full_view.size(): " << full_view.size() << endl ; cout << "full_view.length(): " << full_view.length() << endl ; //Internal data string is not modified. Instead the pointer is moved full_view.remove_prefix(4) ; cout << "full_view: " << full_view << endl ; char arr1[10] ; full_view.copy( arr1, 4 ) ; cout << "arr1: " << arr1 << endl ; //Searching functions are similar to the std::string search functions size_t index = full_view.find("c") ; if ( index != string_view::npos ) cout << "index: " << index << endl ; index = full_view.find("d") ; if ( index != string_view::npos ) cout << "index: " << index << endl ; }