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 回答