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.
JavaScript Code: text_truncate = function(str, length, ending) { if (length == null) { length = 100; } if (ending == null) { ending = '...'; } if (str. length > length) { return str. substring(0, length - ending. length) + ending; } else { return str; } }; console.
Java String trim()The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.
The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With