tonytony
tonytony

Reputation: 2023

Efficient way to truncate string to length N

For example, suppose I have std::string containing UNIX-style path to some file:

string path("/first/second/blah/myfile");

Suppose now I want to throw away file-related information and get path to 'blah' folder from this string. So is there an efficient (saying 'efficient' I mean 'without any copies') way of truncating this string so that it contains "/first/second/blah" only?

Thanks in advance.

Upvotes: 18

Views: 21219

Answers (2)

Kai Petzke
Kai Petzke

Reputation: 2934

While the accepted answer for sure works, the most efficient way to throw away the end of a string is to call the resize method, in your case just:

path.resize(N);

Upvotes: 4

Jon
Jon

Reputation: 437336

If N is known, you can use

path.erase(N, std::string::npos);

If N is not known and you want to find it, you can use any of the search functions. In this case you 'll want to find the last slash, so you can use rfind or find_last_of:

path.erase(path.rfind('/'), std::string::npos);
path.erase(path.find_last_of('/'), std::string::npos);

There's even a variation of this based on iterators:

path.erase (path.begin() + path.rfind('/'), path.end());

That said, if you are going to be manipulating paths for a living it's better to use a library designed for this task, such as Boost Filesystem.

Upvotes: 34

Related Questions