slimjourney
slimjourney

Reputation: 103

Remove substring from both ends of an std::string?

I'm trying to remove some start and end delimiters in a std::string. Is there a built in or better way to do this?

Here is my current way:

std::string sub = "~test.txt~";
std::string str = "~test.txt~The quick brown fox jumps over the lazy dog.~test.txt~";

str = str.substr(sub.length(), str.length() - sub.length() * 2);

Start and end delimiters are exactly the same, and they are located at the very edges.

Expected value is The quick brown fox jumps over the lazy dog..

Upvotes: 1

Views: 397

Answers (2)

Davis Herring
Davis Herring

Reputation: 39758

What you have is correct (for this constrained case) and efficient (assuming that you need a std::string result; std::string_view might be good if you’re using C++17). If it’s ugly, make it a function so that the rest of the code can use

std::string mid=remove2(whole, delim);

…although that’s not efficient in the case of

remove2(whole, "literal")

which allocates memory just to count the characters whose number is already known at compile time. If that matters, you could add an overload that took a length and write

remove2(whole, sizeof("literal")-1)

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

The only problem with your code is that .substr() creates a new std::string, resulting in an expensive allocation (unless the result is small enough for SSO to work).

Use std::string_view to fix that:

str = std::string_view(str).substr(sub.length(), str.length() - sub.length() * 2);

Alternatively, use .assign():

str.assign(str.begin() + sub.length(), str.end() - sub.length());

Upvotes: 2

Related Questions