2
\$\begingroup\$

My main goal is to perform the conversion on a list of strings. Is this a sensible approach or should I refactor?

Please note that I cannot use Boost in my work.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>


char fix_delim(char ch) {
    return ch == '\\' ? '/' : ch;
}

std::string& fix_str(std::string& str) {
   std::transform(str.begin(), str.end(), str.begin(), fix_delim);
   return str;
}

int main() {
   std::list<std::string> files;
   files.push_back("folder\\file1");
   files.push_back("folder\\file2");

   //simple example of fix_delim
   std::string one("folder\\file1");
   std::transform(one.begin(), one.end(), one.begin(), fix_delim);

   //Is this a good way to solve this problem of replacing all instances of \ with / in a list of strings?
   std::transform(files.begin(), files.end(), files.begin(), fix_str);

   return 0;
}
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

With C++11 you can use lambda, otherwise make the helper function static.

If you're tied to std::string and no stock solution, this one is about as good as it gets. I suggest naming it properly like fix_path_separators or along the lines describing its purpose.

\$\endgroup\$
8
\$\begingroup\$

Seems to me that the right algorithm for this job is std::replace:

std::replace(input.begin(), input.end(), '\\', '/');

The easiest way to apply to a collection of strings is probably to use std::for_each with a lambda:

std::for_each(files.begin(), files.end(), 
              [](std::string &s) { std::replace(s.begin(), s.end(), '\\', '/'); });

If you can't use a lambda, you can write a tiny function object instead:

class path_dos2unix {
    void operator()(std::string &s) {  
        std::replace(s.begin(), s.end(), '\\', '/');
    }
};

...and then invoke that:

std::for_each(files.begin(), files.end(), path_dos2unix());
\$\endgroup\$
1
  • \$\begingroup\$ In our work, with multiple platforms to support and waiting for other depts to upgrade it will be a long time till we can use lambdas. But I would love to be able to. \$\endgroup\$
    – arcomber
    Commented May 30, 2013 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.