Strings & string_view
C++ provides two ways to work with text strings: the dynamic std::string class, and the modern C++17 memory-optimized std::string_view.
1 std::string vs. C++17 std::string_view
The standard string libraries handle text dynamically:
- std::string: A class that manages its own memory dynamically. Reallocates heap space when characters are appended.
- std::string_view (C++17): A lightweight, read-only reference window pointing to an existing string. Does not allocate copy memory, making it incredibly fast for parsing operations.
2 String Processing Code
Let's run a program utilizing std::string functions and std::string_view references:
C++ — String processing
▶ Run Code
#include <iostream>
#include <string>
#include <string_view> // C++17
// Pass string_view to prevent copy allocations
void printName(std::string_view sv) {
std::cout << "Viewing name: " << sv << "\n";
}
int main() {
std::string greeting = "Hello, C++ Learners!";
std::cout << "Length: " << greeting.length() << "\n";
std::cout << "Substring: " << greeting.substr(7, 3) << "\n"; // "C++"
// String view optimization demonstration
printName(greeting);
printName("Raw String Literal"); // No memory allocations occur
return 0;
}
3 Code Challenge
Challenge: Write a program that searches for the character '+' inside a `std::string` using the `.find()` method. If found, print the index of the character; otherwise, print a "Not found" statement.