Efficient way to truncate string to length N

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.


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);

Tags:

C++

String