答案 0 :(得分: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;
}