0

Possible Duplicate:
How to split a string in C++?

What is the simplest way of splitting a string based upon a particular character and then inserting the elements into a vector?

Please do not suggest boost.algorithm.split

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361
  • There are many duplicates of this question here. A closer one is here: http://stackoverflow.com/questions/5607589/right-way-to-split-an-stdstring-into-a-vectorstring, but you might find something good in the FAQ: http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – chris May 27 '12 at 14:50
  • 2
    @user997112: please describe what answer you are looking for, instead of what answer you are **not** looking for. Telling us not to suggest boost::algorithm isn't very constructive, because it doesn't tell us if we can suggest another third-party library. Or if we can suggest functionality from the standard library. If you mean "I can't use any part of Boost, so the solution must not rely on that specific library", say that. If you mean "I cannot use *any* third-party library, so the answer must rely only on the C++ standard library", say that. – jalf May 27 '12 at 14:54
  • 2
    If you mean "I can't use a library solution at all. The answer has to be written from scratch", say that. In short, tell us what constraints a valid answer has to satisfy. Simply pointing out *individual* answers which are invalid doesn't really help us answer the question – jalf May 27 '12 at 14:54

1 Answers1

1

There are many ways to parse a string, here is one using substr()

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    string strLine("Humpty Dumpty sat on the wall");
    string strTempString;
    vector<int> splitIndices;
    vector<string> splitLine;
    int nCharIndex = 0;
    int nLineSize = strLine.size();

    // find indices
    for(int i = 0; i < nLineSize; i++)
    {
        if(strLine[i] == ' ')
            splitIndices.push_back(i);
    }
    splitIndices.push_back(nLineSize); // end index

    // fill split lines
    for(int i = 0; i < (int)splitIndices.size(); i++)
    {
        strTempString = strLine.substr(nCharIndex, (splitIndices[i] - nCharIndex));
        splitLine.push_back(strTempString);
        cout << strTempString << endl;
        nCharIndex = splitIndices[i] + 1;
    }

    getchar();

    return 0;
}
james82345
  • 530
  • 4
  • 13