与 std::string 的简单通配符匹配
我有具有以下格式的 std::string
std::string s = "some string with @lable"
我必须找到 '@' 的所有实例,然后在 '@' 之后找到标识符, 该 ID 有一个值(在本例中为“lable”存储在查找表中。然后我将用找到的值替换 @ 和 id。
例如,假设 ID 标签在处理后具有值“1000”该字符串看起来像:
"some string with 1000"
我的第一个版本使用了 boost::regex,但在我被告知接下来的几个版本中不允许使用新库后,我不得不转储它,
所以有一些优雅的方法可以使用普通 std 来做到这一点: :字符串和标准算法?
I have std::string with the follwing format
std::string s = "some string with @lable"
I have to find all instances of '@' and then find the identifier right after the '@' ,
this ID has a value (in this case 'lable' stored for it in a look up table. I will then replace the @ and the id with the found value.
for example suppose the ID label has the value '1000' after the process the string will look like :
"some string with 1000"
my first version used boost::regex, but I had to dump it after I was told that new libs are not allowed in the next few builds.
so is there some elegant way to do it with vanilla std::string and std algorithms ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 std::find 搜索
@
,并获得一对迭代器,形成一个从@
开始到结束的范围在下一个空白字符(或字符串末尾)。然后只需将迭代器传递给 std::string::replace() 即可执行实际的子字符串替换。例如:
如果您还想将制表符或回车符等内容计为空格,则可以将
std::find_if
与::isspace
一起使用。You can use
std::find
to search for the@
, and get a pair of iterators forming a range which begins at the@
and ends at the next white space character (or end of the string). Then just pass the iterators tostd::string::replace()
to do the actual sub-string replacement.For example:
If you also want to count things like tabs or carriage returns as spaces, you can use
std::find_if
along with::isspace
.是的。使用 std::find 搜索 @,然后使用 std::find 搜索空格,并将其间的所有内容复制到一边。
Yes. use std::find to search for @, and then std::find to search for space, and copy everything in between aside.