读书人

在VC6非MFC中string划分数组的有关问题

发布时间: 2013-04-09 16:45:09 作者: rapoo

在VC6非MFC中string划分数组的问题
string str=="126783,2673|1234,46863|34656,2344"
这样一个数组,如何能输入到多维数组string (*s)[2]= new string[3][2];中?

请指点下,感激不尽,已经写错了N次,困扰了半天了。。。。


[解决办法]
嗯,其实 c++ 的也不是太难看。


#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main ()
{
std::string const string = "126783,2673
[解决办法]
1234,46863
[解决办法]
34656,2344";

std::vector<std::vector<std::string>> strings;

typedef typename std::string::const_iterator it_t;
for (it_t lo = string.begin();;++lo)
{
it_t const hi = std::find(lo,string.end(),'
[解决办法]
');
it_t const md = std::find(lo,hi,',');

std::vector<std::string> s;
s.push_back(std::string(lo,md));
s.push_back(std::string(md+1,hi));
strings.push_back(s);

if (string.end() == hi) { break; }
lo = hi;
}

for (size_t i = 0, I = strings.size(); i != I; ++i)
{
for (size_t j = 0, J = strings[i].size(); j != J; ++j)
{
std::cout << strings[i][j] << " ";
}
std::cout << std::endl;
}
}

有 c++11 的话,会更舒服一些,不过写完了以后发现楼主要 vc6 的,就改的简朴了一些。
[解决办法]

// c++ 不太熟,勉强凑个数,逻辑很牵强,期待楼主更新。
string str="126783,2673
[解决办法]
1234,46863
[解决办法]
34656,2344";

string (*s)[2]= new string[3][2];
int iIdx = 0;

string sTmp;

int m = 0, n = 2; // 二维数组下表
while( str.length() > 0 )
{
iIdx = str.find("
[解决办法]
");
if ( iIdx < 0 )
{
sTmp = str;
iIdx = str.length() - 1;
}
else
{
sTmp = str.substr(i,iIdx) ;
}


int idx = 0, k = 0;
if ( sTmp.length() > 0 )
{
s[m][k] = sTmp.substr(idx,sTmp.find(","));
idx = sTmp.find(",");
k++;
s[m][k] = sTmp.substr(idx+1, sTmp.length());

sTmp.clear();
str.erase(0, iIdx+1);
}
m++;
}

[解决办法]
#include <string>
#include <iostream>
#define X 3
#define Y 2



void main()
{
const std::string str = "126783,2673
[解决办法]
1234,46863
[解决办法]
34656,2344";
std::string strResult[X][Y];

std::string::size_type pos1 = 0; // 有效数据开始位置
std::string::size_type pos2 = 0; // 有效数据结束位置

for (int i=0; i!=X; ++i)
{
for (int k=0; k!=Y; ++k)
{
// 从有效数据开始位置pos1查找下一个","和"
[解决办法]
"的位置,取最小值。
pos2 = (str.find(',',pos1)<str.find('
[解决办法]
',pos1))?str.find(',',pos1):str.find('
[解决办法]
',pos1);
// 取得两个符号之间的数据
strResult[i][k] = str.substr(pos1,pos2-pos1);
// 结尾变成下一段数据的起始地点
pos1 = pos2+1;
// 输出结果
std::cout <<"strResult[" << i << "][" << k <<"]=" << strResult[i][k] << std::endl;
}
}

system("pause");
}



输出结果:
strResult[0][0]=126783
strResult[0][1]=2673
strResult[1][0]=1234
strResult[1][1]=46863
strResult[2][0]=34656
strResult[2][1]=2344

读书人网 >C++

热点推荐