我写了一段简单的代码,将字符串按照每个'/'分割并存储到向量中。 我的字符串可能以'/'开头也可能不是,但一定会以'/'结尾。例如,如果我的字符串是:
string="/home/desktop/test/"
I want to <"/","home","desktop","test"> and another example
string="../folder1/folder2/../pic.pdf/"
I want to store <"..","folder1","folder2","..","pic.pdf"
然而,我的代码为我提供了第一个示例的 <" ","home","desktop","test"," ">
和第二个示例的
<"..","folder1","folder2","..","pic.pdf"," ">
有人能帮帮我吗? 这是我用于此的代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string strLine("/cd/desktop/../test/");
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;
}
}