C++ Logo

std-proposals

Advanced search

Re: Add first and last to the std::string_view

From: kang hewill <hewillk_at_[hidden]>
Date: Sat, 23 Jan 2021 00:48:34 +0800
Very appreciate your feedback.
I think "last" trivially means obtained last N characters:

  assert("hello_world"sv.first("hello"sv.size()) == "hello");
  assert("hello_world"sv.last("world"sv.size()) == "world");

which the equivalent poisoned "substr" is:

  assert("hello_world"sv.substr(0, "hello"sv.size()) == "hello");
  assert("hello_world"sv.substr("hello_"sv.size()) == "world");

Noticed that "last" behavior is not like Ranges-v3 "drop":
  assert("hello_world"sv.last(5) == "orld");
  assert("hello_world"sv.drop(5) == "_world");

and C++17 already has the drop front/back facilities which
is remove_prefix/remove_suffix
   auto s = "hello_world"sv;
   s.remove_prefix(5);
   assert(s == "_world");

and thank you for the last demonstration which shows that the fallible copy
constructor that I never thought that. :)

Arthur O'Dwyer via Std-Proposals <std-proposals_at_[hidden]> 於
2021年1月22日 週五 下午9:31寫道:

> On Fri, Jan 22, 2021 at 6:27 AM Nicholas Schwab via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> Hi,
>>
>> for your specific example, the in my opinion best way would be
>>
>> static_assert("hello world"sv.starts_with("hello"));
>>
>> which is possible since C++20. But in general I agree, that it would be
>> nice to have these member functions. Specifically, I dislike calls to
>> string_view::substr with one argument (which is equivalent to your
>> proposed string_view::last):
>>
>> "hello_world".substr(5);
>>
>> This returns "_world"sv, but I do not find that obvious from the name
>> only.
>
>
> Absolutely. However, notice that `.substr(5)` isn't `.last(5)`; it's
> `.last_all_but(5)`.
> The vocabulary terms for "first" and "last" here, since Ranges-v3, are
> actually "take" and "drop":
> assert("hello_world"sv.take(5) == "hello");
> assert("hello_world"sv.drop(5) == "_world");
> assert("hello_world"sv.drop_all_but(5) == "world");
>
> The standard library was "poisoned" early on with APIs (like
> single-argument .substr(5)) that take integers to indicate either "start
> here" or "go until here" with no explanation. For example, it was recently
> brought to my attention that
>
> // https://godbolt.org/z/69xY4x
> assert(std::string("hello_world", 5) == "hello");
> assert(std::string("hello_world"s, 5) == "_world");
>
> –Arthur
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2021-01-22 10:48:50