每 n 行将字符串转换为多个字符串
String To Multiple Strings Every Nth Line
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
会是一个更好的名字。
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组