c++ - 如何在 C++ 中解析逗号分隔的字符串,其中一些元素用逗号引用?
问题描述
我有一个逗号分隔的字符串,我想将它存储在字符串向量中。字符串和向量是:
string s = "1, 10, 'abc', 'test, 1'";
vector<string> v;
理想情况下,我希望在没有单引号的情况下存储字符串 'abc' 和 'test, 1',如下所示,但我可以使用单引号来存储它们:
v[0] = "1";
v[1] = "10";
v[2] = "abc";
v[3] = "test, 1";
解决方案
您需要在这里做的是让自己成为一个解析器,可以按照您的意愿进行解析。这里我为你做了一个解析函数:
#include <string>
#include <vector>
using namespace std;
vector<string> parse_string(string master) {
char temp; //the current character
bool encountered = false; //for checking if there is a single quote
string curr_parse; //the current string
vector<string>result; //the return vector
for (int i = 0; i < master.size(); ++i) { //while still in the string
temp = master[i]; //current character
switch (temp) { //switch depending on the character
case '\'': //if the character is a single quote
if (encountered) encountered = false; //if we already found a single quote, reset encountered
else encountered = true; //if we haven't found a single quote, set encountered to true
[[fallthrough]];
case ',': //if it is a comma
if (!encountered) { //if we have not found a single quote
result.push_back(curr_parse); //put our current string into our vector
curr_parse = ""; //reset the current string
break; //go to next character
}//if we did find a single quote, go to the default, and push_back the comma
[[fallthrough]];
default: //if it is a normal character
if (encountered && isspace(temp)) curr_parse.push_back(temp); //if we have found a single quote put the whitespace, we don't care
else if (isspace(temp)) break; //if we haven't found a single quote, trash the whitespace and go to the next character
else if (temp == '\'') break; //if the current character is a single quote, trash it and go to the next character.
else curr_parse.push_back(temp); //if all of the above failed, put the character into the current string
break; //go to the next character
}
}
for (int i = 0; i < result.size(); ++i) {
if (result[i] == "") result.erase(result.begin() + i);
//check that there are no empty strings in the vector
//if there are, delete them
}
return result;
}
这会根据需要解析您的字符串,并返回一个向量。然后,您可以在程序中使用它:
#include <iostream>
int main() {
string s = "1, 10, 'abc', 'test, 1'";
vector<string> v = parse_string(s);
for (int i = 0; i < v.size(); ++i) {
cout << v[i] << endl;
}
}
并正确打印出:
1
10
abc
test, 1
推荐阅读
- c++ - 在 C++ 中获取命名空间名称的任何可移植技巧?
- json - 如何使用对象映射器从 JSON 字符串中删除反斜杠
- android - 使用 addView 时无法区分布局中的视图
- demandware - 从 mac 10.12.06 在 Eclipse 上运行需求软件项目时面临构建失败
- wpf - 带有 ObservableCollection 的菜单的纯 XAML?
- c# - 玩家旋转,相机旋转,但 x,y,z 保持不变?
- android - 如何通过 Android 应用程序将照片保存在手机或 SD 卡中
- r - 如何在 R 中重新排列数据表的格式?
- c# - 如何使用 c# asp.net 查找客户端 PC 的 MAC 地址?
- sql-server - SQL 错误:将表达式转换为数据类型 int 的算术溢出错误