Nov 9, 2025

[C++] Use string_view _sv over raw char string

Reference:
https://youtu.be/jXQ6WtYmfZw?si=B_C-UXBVCFpAODVh&t=4428


std:: string s("the foo and the bar");
std:: println("{}", std::ranges::contains_subrange(s, "foo" ));
This won't work due to C-style string literal "foo" is actually a range of four characters: 
['f', 'o', 'o', '\0'] 

Easy fix:
#include <iostream>
#include <string>
#include <string_view>
#include <ranges>
#include <print> // C++23 for std::println

int main() {
    using namespace std::literals; // Enables the "sv" suffix

    std::string s("the foo and the bar");
    
    // "foo"sv creates a std::string_view of length 3.
    // This will now print "true".
    std::println("{}", std::ranges::contains_subrange(s, "foo"sv)); 
}

or C++23:
std::string s("the foo and the bar");

// This is the simplest way and does what you expect.
// It will print "true".
std::println("{}", s.contains("foo"));

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.