我有以下格式的 std::string
std::string s = "some string with @lable"
我必须找到 '@' 的所有实例,然后在 '@' 之后找到标识符, 这个 ID 有一个值(在本例中,'lable' 存储在查找表中。然后我将用找到的值替换 @ 和 id。
例如,假设 ID 标签在处理后的值为“1000”,字符串将如下所示:
"some string with 1000"
我的第一个版本使用了 boost::regex,但在我被告知在接下来的几个构建中不允许使用新库后,我不得不放弃它。
那么有没有一些优雅的方法可以用普通的 std::string 和 std 算法来做到这一点?
最佳答案
您可以使用std::find
来搜索@
,并得到一对迭代器,形成从@
开始的范围> 并在下一个空白字符(或字符串结尾)处结束。然后只需将迭代器传递给 std::string::replace()
即可进行实际的子字符串替换。
例如:
std::string s = "some string with @lable";
std::string::iterator beg = std::find(s.begin(), s.end(), '@');
std::string::iterator end = std::find(beg, s.end(), ' ');
s.replace(beg, end, "whatever");
如果您还想将制表符或回车之类的东西计为空格,您可以使用 std::find_if
和 ::isspace
。
关于c++ - 与 std::string 的简单通配符匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1896656/