我编写了一个简单的代码,将字符串从每个“ /”中拆分出来并存储为向量。我的字符串可能以/开头,definetelly将以/结尾。例如,如果我的字符串是:
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;
}
}
在代码中应该做的一些事情可以解决这个问题,为此可能会有一个更好,更优雅的解决方案。
#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
if(nLineSize!=0 && strLine[0]=='/')
{
splitLine.push_back(strLine.substr(0,1));
nCharIndex++;
}
for(int i = 1; i < nLineSize; i++)
{
if(strLine[i] == '/')
splitIndices.push_back(i);
}
// fill split lines
for(int i = 0; i <int(splitIndices.size()); i++)
{
strTempString = strLine.substr(nCharIndex, (splitIndices[i] - nCharIndex));
splitLine.push_back(strTempString);
nCharIndex = splitIndices[i] + 1;
}
}
编辑:稍微清除了代码,您现在可以删除添加最后一个索引部分。
编辑2:
一个可能更美观的解决方案可能是删除ncharcounter并为此使用拆分索引。如果第一个字符不是('/'),则可以将第一个值存储为'-1';如果不是,则可以将其存储为('0')。
string strLine("/cd/desktop/../test/");
string strTempString;
vector<int> splitIndices;
vector<string> splitLine;
int nLineSize = strLine.size();
// find indices
splitIndices.push_back(-1);
if(nLineSize!=0 && strLine[0]=='/')
{
splitLine.push_back(strLine.substr(0,1));
splitIndices[0]=0;
}
for(int i = 1; i < nLineSize; i++)
{
if(strLine[i] == '/')
splitIndices.push_back(i);
}
// fill split lines
for(int i = 1; i <int(splitIndices.size()); i++)
{
strTempString = strLine.substr(splitIndices[i-1]+1, (splitIndices[i] - (splitIndices[i-1]+1) ));
splitLine.push_back(strTempString);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句