0

重複の可能性:
C++ で文字列を分割する方法は?

特定の文字に基づいて文字列を分割し、要素をベクトルに挿入する最も簡単な方法は何ですか?

boost.algorithm.split を提案しないでください

4

1 に答える 1

1

文字列を解析するには多くの方法がありますが、ここでは 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;
}
于 2012-05-27T15:33:05.540 に答える