Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to truncate string to length N

Tags:

c++

string

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.

like image 707
tonytony Avatar asked May 12 '12 17:05

tonytony


People also ask

How do you truncate a string to a specific length if it is longer?

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.

How do you trim the length of a string?

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.

How do you short a string in JavaScript?

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.


1 Answers

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.

like image 155
Jon Avatar answered Sep 18 '22 15:09

Jon