0

I am quite new to C++ and i think i made a tiny mistake somewhere in this bit of code. I failed to spot it so far. I hope you can help me, and tell me how/where/why it is wrong? Many thanks in advance.

The code:

std::vector<std::string> spliter(const std::string& s, char delimiter)
{
        std::vector<std::string> result;

        size_t start = 0;
        for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start))
        {
            result.push_back( s.substr(start,i-start) );
            start = i+1;
        }
        iprintf("\x1b[2J");
        printf("\x1b[4;0HDone Splitting Text.");
        swiWaitForVBlank();
        return result;
}

Parameters given: s = "$ 00-000 SS ''Prologue'' CF N00-001 V 1 MP 20" delimiter = ' ' (a space)

Expected result:

result[0] = $
result[1] = 00-000
result[2] = SS
etc.

Current wrong result:

result[0] = 
result[1] = 
result[2] = 00-000
etc.

Any help is greatly appreciated!

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Smileynator
  • 677
  • 8
  • 24

2 Answers2

2

I believe the problem is in the loop.. You start from 0, and the first thing that you push is from 0 to 0.

    size_t start = 0;
    for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start))
    {
        result.push_back( s.substr(start,i-start) );
        start = i+1;
    }

instead if you start i from s.find(delimiter, start) it should work. Example here..

vidit
  • 6,293
  • 3
  • 32
  • 50
1

Here is a possible way to fix your algorithm:

#include <vector>
#include <string>

std::vector<std::string> spliter(const std::string& s, char delimiter)
{
    std::vector<std::string> result;

    std::string::size_type start = 0;
    auto pos = s.find(delimiter, 0);
    while (pos != std::string::npos)
    {
        result.push_back(s.substr(start, pos - start));
        start = pos + 1;
        pos = s.find(delimiter, start);
    }

    if (start < s.length())
    {
        result.push_back(s.substr(start));
    }

    return result;
}

And here is a live example of this algorithm giving the correct output for your test string.

Notice, that you could generalize this to work with a string as a delimiter rather than a single character just by changing the type of splitter's second argument (and passing " " instead of ' ', of course).

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • This one works perfectly! i had to change 'auto' to 'std::size_t' because of how my compiler works, but this is great! I will take some time to analyze what exactly gone wrong as Drew and vidit told me. Thanks again! – Smileynator Mar 31 '13 at 22:51
  • This i noticed, 'size_t' seems to function just as well! I find this way easier to read as well. Next time i will not use a for loop like that. It will just cause confusion. – Smileynator Mar 31 '13 at 22:58