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.
['https://Stackoverflow.com/questions/10565752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1096537/']
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`](http://en.cppreference.com/w/cpp/string/basic_string/rfind) or [`find_last_of`](http://en.cppreference.com/w/cpp/string/basic_string/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](http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/index.htm).
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);

```