Smileynator
Smileynator

Reputation: 697

C++ Properly split text on char

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!

Upvotes: 0

Views: 135

Answers (2)

vidit
vidit

Reputation: 6451

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..

Upvotes: 2

Andy Prowl
Andy Prowl

Reputation: 126452

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).

Upvotes: 1

Related Questions