【发布时间】:2021-06-25 04:27:11
【问题描述】:
我必须解析一个长字符串并将字符串的各个部分分配给不同的变量。我以一种非常迂回的方式做到了这一点,效果很好,但没有我想要的那么好。有没有更有效的循环方式?
我正在做的是从 studentdata 数组的第一个索引开始,在有逗号的地方停止,然后存储它们之间的内容,直到我到达每个字符串的末尾。
int rhs = studentData.find(",");
string studentID = studentData.substr(0, rhs);
int lhs = rhs + 1;
rhs = studentData.find(",", lhs);
string firstName = studentData.substr(lhs, rhs - lhs);
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
string lastName = studentData.substr(lhs, rhs - lhs);
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
string eMail = studentData.substr(lhs, rhs - lhs);
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
int age = stoi(studentData.substr(lhs, rhs - lhs));
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
int daysInCourse1 = stoi(studentData.substr(lhs, rhs - lhs));
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
int daysInCourse2 = stoi(studentData.substr(lhs, rhs - lhs));
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
int daysInCourse3 = stoi(studentData.substr(lhs, rhs - lhs));
lhs = rhs + 1;
rhs = studentData.find(",", lhs);
to_string(degreeProgram) = studentData.substr(lhs, rhs - lhs);
要解析的字符串示例:
"A1,John,Smith,John1989@gm ail.com,20,30,35,40,SECURITY",
"A2,Suzan,Erickson,Erickson_1990@gmailcom,19,50,30,40,NETWORK",
感谢您向不同来源提供任何反馈或转发,以提供更好的洞察力。
【问题讨论】:
-
这个长字符串有特定的模式吗?在这种情况下,您可以查看std::regex
-
您也应该在问题中包含一些您想要解析的实际字符串。只需edit 问题并将它们放在代码块中。
-
回想起来,我明白这应该是显而易见的。对不起。
-
谢谢,泰德。我对编码很陌生,所以我没有意识到有一个缩写。感谢您的帮助!