0

I need to parse the path part of a URL for a "router" as part of a REST web service. I'm using the PION library for handling HTTP requests. This library does not seem to have any functionality for retrieving parts of the URL path - or so it seems. I cannot find another library that does this. http://www.w3.org/Library/src/HTParse.c does not give parts of the path for example.

Is there a quicker, more robust way of doing this:

std::vector<std::string> parsePath(std::string path)
{
    std::string delimiter = "/";
    std::string part = "";
    std::size_t firstPos = 0;
    std::size_t secondPos = 0;
    std::vector<std::string> parts;

    while (firstPos != std::string::npos)
    {
        firstPos = path.find(delimiter, firstPos);
        secondPos = path.find(delimiter, firstPos + 1);
        part = path.substr(firstPos + 1, (secondPos - 1) - firstPos);
        if (part != "") parts.push_back(part);
        firstPos = secondPos;
    }

    return parts;
}
d-_-b
  • 6,555
  • 5
  • 40
  • 58
  • Perhaps [this](http://stackoverflow.com/q/2616011/777186) helps. The method suggested there does not return a `vector` as such, but converting to a `vector` if necessary shouldn't be difficult. – jogojapan Apr 11 '12 at 03:01
  • Related: http://stackoverflow.com/questions/2616011/easy-way-to-parse-a-url-in-c-cross-platform – HostileFork says dont trust SE Apr 11 '12 at 03:02
  • Yeah, I saw that, but they are parsing a URL. So they want all sorts of parameters to be deduced. I only want to split up the path so I can read each one separately and deduce the route. – d-_-b Apr 11 '12 at 04:15

1 Answers1

3

If you have the freedom to use Boost, the easiest way to parse filesystem paths would be to use the filesystem library, which has the advantage of being platform-independent and handling both POSIX and Windows path variants:

boost::filesystem::path p1("/usr/local/bin");
boost::filesystem::path p2("c:\\");
std::cout << p1.filename() << std::endl; // prints "bin"
std::cout << p1.parent_path() << std::endl; // prints "/usr/local"

To iterate through each element of the path, you can use a path iterator:

for (auto const& element : p1)
    std::cout << element << std::endl;

prints

"/"
"usr"
"local"
"bin"

Without Boost, choose one of the many ways to parse a delimited string.

Community
  • 1
  • 1
mavam
  • 12,242
  • 10
  • 53
  • 87
  • I saw the boost::filesystem::path. How would I get each part of the path? – d-_-b Apr 11 '12 at 04:08
  • Check out [this table](http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/reference.html#Path-decomposition-table). I updated the answer with an example. – mavam Apr 11 '12 at 04:11
  • Yup, a path behaves like a container in that it has `begin()` and `end()` member functions returning a `path_iterator`. – mavam Apr 11 '12 at 06:17