我想将字符串拆分为二维字符串,并将数组的第一个索引除以仅存储 3 个单词的引用,第二个索引以存储单词我读过这篇文章类似于它,但它对我来说不是那么好 StackOver Flow,为了正确理解它,我举了一个例子。
例如字符串 a="你好,我在写 c++ 代码";
我想将其转换为
string b[100][3];
b[0][1]="hello";
b[0][2]="I";
b[0][3]="am";
b[1][1]="writing";
b[1][2]="c++";
b[1][3]="code";
这有效,我认为可以做你想要的:
#include <array>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
std::vector< std::array< std::string, 3 > > split( std::string const &s )
{
std::vector< std::array< std::string, 3 > > rv;
std::array< std::string, 3 > a;
int i = 0;
size_t first = 0, len = s.size();
while (first < len)
{
size_t last = s.find( ' ', first );
if (last == std::string::npos)
last = len;
a[i++] = s.substr( first, last - first );
first = last + 1;
if (i == 3)
{
rv.emplace_back( std::move( a ) );
i = 0;
}
}
if (i)
rv.emplace_back( std::move( a ) );
return rv;
}
int main()
{
auto v = split( "Hello I am writing c++ code" );
for (auto const &a : v)
std::cout << "'" << a[0] << "'; '" << a[1] << "'; '" << a[2] << "'n";
return 0;
}
向量的向量是解决您问题的一个很好且优雅的解决方案。这是针对您的问题的建议解决方案。
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
vector<vector<string>> strTo2DStr(const string& str, const int& r, const int& c)
{
vector<vector<string>> mat;
int rows(r), cols(c);
vector<string> words;
istringstream ss(str);
copy(istream_iterator<string>(ss),istream_iterator<string>(),back_inserter(words));
int counter(0);
for ( int i(0); i < rows; ++i ){
vector<string> temp;
for ( int j(0); j < cols; ++j){
if ( counter < words.size() )
temp.push_back(words[counter++]);
else
temp.push_back("");
}
mat.push_back(temp);
}
return mat;
}
int main ()
{
string str("Hello I am writing c++ code");
int rows(3), cols(3);
vector< vector<string> > mat = strTo2DStr(str,rows,cols);
cout << str << endl << endl;
for ( int i(0); i < rows; ++i )
for ( int j(0); j < cols; ++j)
cout << "mat[" << i << "]["<< j << "]= " << mat[i][j] << " " << endl;
return 0;
}
该解决方案非常灵活,因为您可以选择行数和列数。结果是
Hello I am writing c++ code
mat[0][0]= Hello
mat[0][1]= I
mat[0][2]= am
mat[1][0]= writing
mat[1][1]= c++
mat[1][2]= code
mat[2][0]=
mat[2][1]=
mat[2][2]=