每 n 行将字符串转换为多个字符串

String To Multiple Strings Every Nth Line

本文关键字:字符串 转换      更新时间:2023-10-16

SOLUTION 感谢 1111...

vector<std::string> split_at_line(string str, int lines) {
 vector<std::string> nine_ln_strs;
 string temp;
 stringstream ss;
 int i = 0;
 while(i != str.length()) {
     ss << str.at(i);
     if(i == lines) {
        lines += lines;
        getline(ss,temp);
        nine_ln_strs.push_back(temp);
        ss.clear();
        temp.clear();
     }
     if(i+lines > str.length()) {
        getline(ss,temp);
        nine_ln_strs.push_back(temp);
        ss.clear();
        temp.clear();
        break;
     }
     i++;
 }
 return nine_ln_strs;

}

====

===============================================

我今天试图练习和学习如何使用多维数组,我遇到了一个问题。 我不知道如何将一个字符串分成多个字符串,每 N 行。 我已经搜索了网络,但似乎只有空格和令牌的示例。 有没有办法做我想做的事情?

例:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const int five = 5;
int test[][five] = {
{ 0, 0, 1, 0, 0 },
{ 0, 1, 1, 0, 0 },
{ 0, 2, 1, 0, 0 }
};
int main() {
stringstream result;
int a = sizeof test / sizeof ( test[0] );
cout << a << endl;
int b = 5;
for ( int i = 0; i < a; i++ ) {
    for ( int j = 0, inc = 0 ; j < b; j++, inc++ ) {
        if(inc == 2) {
            result << hex << setfill ('0') << setw(4) << (int)test[i][j];
        } else {
            result << hex << setfill ('0') << setw(2) << (int)test[i][j];
        }
    }
}
string s = result.str();
cout << s << endl;
// split the string into segments of every 000000000000 and store them into a new string each time, or another array
   int z;       // hold
   cin >> z;
   return 0;
}

可能有更好的方法,但这应该有效

 std::vector<std::string> split_at_line(const std::string& str, unsigned lines) {
     std::vector<std::string> nine_ln_strs;
     std::istringstream ss(str);
     std::string temp, t2;
     while(ss) { //whilst there is still data
         //get nine lines
         for(unsigned i=0; i!=lines && std::getline(ss, t2); ++i) {          
             temp+=t2;
         }
         //add block to container
         nine_ln_strs.push_back(temp));
     }
     //return container
     return nine_ln_strs;
 }

PS:C 数组不是很好,尽可能尝试使用容器。此外,将称为five的常量定义为5也不是很有帮助。在这里使用变量的想法是,以便以后可以更改它,如果您将 5 的值更改为 6,那会很奇怪。 test_sz会是一个更好的名字。