0

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

Waqar
  • 8,558
  • 4
  • 35
  • 43
Sergio
  • 891
  • 9
  • 27
  • 1
    Like [this](https://en.cppreference.com/w/cpp/string/basic_string_view/substr)? –  Jun 15 '20 at 12:00
  • 1
    Please explain specifically how"too long" is defined. Also, whether you only want to format output, or you actually need a `string_view` (there might be other, display-only ways). – underscore_d Jun 15 '20 at 12:05

1 Answers1

2

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);
Waqar
  • 8,558
  • 4
  • 35
  • 43