COMMON: Added firstPathComponents() method.

A better name is welcome
This commit is contained in:
Eugene Sandulenko 2022-03-14 20:44:12 +01:00
parent cc9f49e89c
commit 498b2ca3a0
No known key found for this signature in database
GPG key ID: 014D387312D34F08
2 changed files with 37 additions and 0 deletions

View file

@ -543,6 +543,29 @@ String lastPathComponent(const String &path, const char sep) {
return String(first, last); return String(first, last);
} }
String firstPathComponents(const String &path, const char sep) {
const char *str = path.c_str();
const char *last = str + path.size();
// Skip over trailing slashes
while (last > str && *(last - 1) == sep)
--last;
// Path consisted of only slashes -> return empty string
if (last == str)
return String();
// Now scan the whole component
const char *first = last - 1;
while (first > str && *first != sep)
--first;
if (*first == sep)
first++;
return String(str, first);
}
String normalizePath(const String &path, const char sep) { String normalizePath(const String &path, const char sep) {
if (path.empty()) if (path.empty())
return path; return path;

View file

@ -290,6 +290,20 @@ extern char *trim(char *t);
*/ */
String lastPathComponent(const String &path, const char sep); String lastPathComponent(const String &path, const char sep);
/**
* Returns the first components of a given path (complementary to lastPathComponent)
*
* Examples:
* /foo/bar.txt would return '/foo/'
* /foo/bar/ would return '/foo/'
* /foo/./bar// would return '/foo/./'
*
* @param path the path of which we want to know the last component
* @param sep character used to separate path components
* @return The all the components of the path except the last one.
*/
String firstPathComponents(const String &path, const char sep);
/** /**
* Normalize a given path to a canonical form. In particular: * Normalize a given path to a canonical form. In particular:
* - trailing separators are removed: /foo/bar/ -> /foo/bar * - trailing separators are removed: /foo/bar/ -> /foo/bar