这是用 C++ 编写的。假设我有一个看起来像这样的字符串 "[05]some words here [13]some more words here [17]and so on"
我想把这个字符串分割成Map<int, std::string>
以数字作为键,将直到下一个代码的文本作为值。括号将被完全忽略。
到目前为止,我一直在使用标准库和 SDL(我正在制作一个小游戏),但我愿意安装 boost 或任何其他有帮助的库。
我的第一个想法是使用一些 Boosts Regex 函数来进行某种正则表达式查找和替换,或者简单地将其转换为字符数组,遍历每个字符查找括号并记录其中的数字,但这似乎好像它效率很低,特别是因为我确信在 C++ 中可能有一种流行的方法可以做到这一点。
最佳答案
您可以使用 regex_token_iterator为了这。基本思想如下:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <regex>
using namespace std;
map<int, string> extract( const std::string & s )
{
map<int, string> m;
static const regex r( "\\s*\\[(\\d+)\\]" );
sregex_token_iterator tok( s.begin(), s.end(), r, { -1, 1 } );
tok++; // Skip past the first end-of-sequence iterator.
for( sregex_token_iterator end; tok != end; )
{
int num = stoi( *tok, nullptr, 10 );
if( ++tok != end )
{
m.emplace( make_pair( num, *tok++ ) );
}
}
return m;
}
int main()
{
auto m = extract("[05]some words here [13]some more words here [17]and so on");
for( auto & p : m ) cout << p.first << ": '" << p.second << "'" << endl;
return 0;
}
这里,这是搜索并提取模式 \s*\[(\d+)\]\s*
,这意味着它将删除方括号前后的所有空格,并且创建一个匹配组以匹配至少一位数字。
通过在迭代器上使用 {-1, 1}
,我们要求迭代序列提供匹配之前的所有文本,然后是匹配组 1。
输出:
5: 'some words here'
13: 'some more words here'
17: 'and so on'
工作示例是 here
关于c++ - 将字符串中的数据提取到映射中的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881407/