Search code examples
c++c++17string-view

Substring console output using std::string_view


Is it possible to substring console output of an std::string using std::string_view?

For example:

std::string toolong {"this is a string too long for me"};  
std::string_view(toolong);
// do something...

expected console output: this is a string


Solution

  • Yes, it's called substring-ing.

    std::string toolong {"this is a string too long for me"};  
    std::string_view view(toolong);
    
    std::cout << view.substr(0, 16);
    

    Alternatively, you can use the remove_prefix() and remove_suffix() methods as well.

    Example:

    view.remove_suffix(16); // view is now "this is a string"
    
    view.remove_prefix(5); // view is now -> "is a string"
    

    If you want to do it in-place without creating a variable of string_view, use substr()

    std::string toolong {"this is a string too long for me"};  
    std::cout << std::string_view (toolong).substr(0, 16);