-3

I want to split the string "/1/2/3/4" to four parts, ie 1,2,3,4. I am using boost to split the string

#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>

int main(int argc, char** argv) {

        std::vector<std::string> v;
        //boost::split(v, argv[1], boost::is_any_of("/"));
        boost::split(v, argv[1], [](char c){return c == '/';});
        for( auto i : v )
                std::cout << i << ' ';
        std::cout << std::endl;

        std::cout << v.size() << std::endl;

        return 0;

}

when I run I am taking an extra empty word in my vector

[oracle@localhost split]$ ./a.out /1/2/3/4
 1 2 3 4 
5

due to the fact that my word (/1/2/3/4) starts with the delimiter. How do I resolve this issue? I want the vector to hold 1,2,3,4 only.

cateof
  • 6,608
  • 25
  • 79
  • 153
  • 2
    Easy solution: after you parse run through the vector and remove the empty elements. `v.erase(std::remove(v.begin(), v.end(), ""), v.end());`. This even lets you handle `1/2/3////4` – NathanOliver Aug 23 '17 at 16:06
  • @NathanOliver I see your point but I may need the empty intervals in some cases. Only the first causes problems to me. Can I use a "character set" with boost::is_any_of? – cateof Aug 23 '17 at 16:13
  • Seriously, I don't understand the downvotes. I want to split a string that starts with the delimiter character. – cateof Aug 23 '17 at 16:14
  • Not sure. I guess because the simple thing to do would be to start after the first character. – NathanOliver Aug 23 '17 at 16:15
  • 3
    Not a downvoter but it doesn't seem like you put much thought into solving the problem yourself. – Kevin Aug 23 '17 at 16:15
  • My code is a small snippet. In real cases, I don't have argv[1] but an std::string. I don't want to use substr() since it creates a new string. I could start with the index=1 for the string, but how can I do this without creating an new std::string? – cateof Aug 23 '17 at 16:19
  • @cateof In that case I think you would be much better off writing your own function and discard the first element if it is blank. You can see how to write your own here: https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – NathanOliver Aug 23 '17 at 16:24

1 Answers1

3

To just throw away the first character:

boost::split(v, argv[1] + 1, [](char c){return c == '/';});

But remember to make sure that the strlen of argv[1] is >0 at this point

N00byEdge
  • 1,106
  • 7
  • 18