C++ Logo

std-proposals

Advanced search

[std-proposals] Adding a .slice() method to std::basic_string

From: Rhidian De Wit <rhidiandewit_at_[hidden]>
Date: Tue, 12 Mar 2024 21:21:35 +0100
Hi,

C++ parsing has gotten a lot better since C++20 and C++23 with the
introduction of *string::ends_with()* and *string::contains()*, but I feel
like there's more to be gained.
Python has a great feature called *string slicing* in the form of:

*testString = 'Hello World!' *
*print(* *testString**[1:11]) # prints 'ello World'*

We can't mimic Python's exact syntax (to my knowledge), but I feel like
this would be a great gain over the current *basic_string::substr() *since
this new function *basic_string::slice()* would have a similar API to
Python's string slicing; requiring a starting index and an ending index.

The full function syntax would look something like:

*string string::slice(size_t start, size_t end);*

And be used like this:

*std::string testString{ "Hello World!" };*
*std::cout << testString.slice(1, 11); // prints 'ello World'*

Sincerely,
Rhidian De Wit

Received on 2024-03-12 20:21:49