[英]How can I extract pairs of values from a string in C++
我有一個具有這種格式的字符串:
"name1":1234 " name2 " : 23456 "name3" : 12345
等等...
我嘗試使用嵌套的while循環和兩個整數來存儲要在string::substr
使用的位置和長度,但是我找不到正確的方法來獲取它(大多數情況下,我最終都退出了字符串)。
不需要存儲這些值,因為我可以在調用它們后立即調用一個函數來處理它們。
到目前為止,這是我所做的:
void SomeClass::processProducts(std::string str) {
unsigned int i = 0;
std::string name;
while (i < str.length()) {
if (str[i] == '\"') {
int j = 1;
while (str[i + j] != '\"') {
j++;
}
name = str.substr(i + 1, j - 1);
i += j;
}
else if (str[i] >= '0' && str[i] <= '9') {
int j = 1;
while (str[i + j] >= '0' && str[i + j] <= '9') {
j++;
}
//This is just processes the values
std::stringstream ss;
std::string num = str.substr(i, j);
ss.str(num);
int products = 0;
ss >> products;
if (products == 0) {
Util::error(ERR_WRONG_PRODUCTS);
}
int pos = getFieldPos(name);
if (pos == -1) {
Util::error(ERR_WRONG_NAME);
}
else {
fields[pos].addProducts(products);
}
i += j;
}
i++;
}
}
提前致謝。
不幸的是,C ++沒有開箱即用的強大字符串解析能力。 這就是為什么有很多方法可以執行此類任務的原因。
但是,C ++確實提供了幫助的工具。 因此我們可以使用它們,至少可以避免手動循環。
在開始之前,我想提請您注意以下事實:在處理用戶輸入時,我們必須格外小心以驗證輸入。
我選擇的解決方案所需的模塊是:
"name" : value
)。 為此,我選擇了std::find
。 也可以使用正則表達式。 value
解析為數字。 為此,我們可以使用std::stoi
。 看看下面為什么還不夠。 std::stoi
問題,因為它很高興地接受尾隨的非空白而沒有大驚小怪。 因此,例如123 invalid
將被解析為123
。 這就是我在它周圍使用小包裝parse_string_to_int
好的,我們繼續:
小幫手:
auto parse_string_to_int(const std::string& str)
{
std::size_t num_processed = 0;
int val = std::stoi(str, &num_processed, 10);
auto next_non_space = std::find_if(str.begin() + num_processed, str.end(),
[](char ch) { return !std::isspace(ch); });
if (next_non_space != str.end())
throw std::invalid_argument{"extra trailing characters in parse_string_to_int"};
return val;
}
struct Product_token
{
std::string name;
int value;
};
auto get_next_product(std::string::const_iterator& begin, std::string::const_iterator end)
-> Product_token
{
// match `"name" : value "`
auto name_open_quote = std::find(begin, end, '\"');
auto name_close_quote = std::find(name_open_quote + 1, end, '\"');
auto colon = std::find(name_close_quote, end, ':');
auto next_token_open_quote = std::find(colon, end, '\"');
if (name_close_quote == end || name_close_quote == end || colon == end)
{
// feel free to add more information regarding the error.
// this is just the bare minimum to accept/reject the input
throw std::invalid_argument{"syntax error on parsing product"};
}
// advance to next token
begin = next_token_open_quote;
return Product_token{{name_open_quote + 1, name_close_quote},
parse_string_to_int({colon + 1, next_token_open_quote})};
}
auto process_products(const std::string& str)
{
auto begin = str.begin();
while (begin != str.end())
{
auto product = get_next_product(begin, str.end());
cout << '"' << product.name << "\" = " << product.value << endl;
}
}
int main()
{
auto str = R"("name1":1234 " name2 " : 23456 "name3" : 12345)"s;
try
{
process_products(str);
}
catch (std::exception& e)
{
cerr << e.what() << endl;
}
}
查看有關ideone的完整代碼
只要知道格式,提取數據就很容易。 首先從字符串中刪除所有引號或冒號,然后用空格替換。 現在,該字符串由空格分隔。
#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string str("\"name1\":1234 \" name2 \" : 23456 \"name3\" : 12345");
cout << str << endl;
// remove ':' and '"' and replace them by space
std::replace_if(str.begin(), str.end(), ispunct, ' ');
istringstream ss(str);
vector<string> words;
// store data as name and number in vector<string>
copy(istream_iterator<string>(ss),istream_iterator<string>(),back_inserter(words));
for (int i(0); i < words.size(); i+=2)
cout << "name: " << words[i] << " number: " << words[i+1] << endl;
return 0;
}
結果是
"name1":1234 " name2 " : 23456 "name3" : 12345
name: name1 number: 1234
name: name2 number: 23456
name: name3 number: 12345
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.