与 std::string 的简单通配符匹配

发布于 2024-08-15 12:17:45 字数 395 浏览 1 评论 0原文

我有具有以下格式的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

断舍离 2024-08-22 12:17:45

您可以使用 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 一起使用。

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 to std::string::replace() to do the actual sub-string replacement.

For example:

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");

If you also want to count things like tabs or carriage returns as spaces, you can use std::find_if along with ::isspace.

自此以后,行同陌路 2024-08-22 12:17:45

是的。使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文