std::string 比较(检查字符串是否以另一个字符串开头)
我需要检查 std:string 是否以“xyz”开头。 如何在不搜索整个字符串或使用 substr() 创建临时字符串的情况下执行此操作?
I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会使用比较方法:
I would use compare method:
一种可能更符合标准库精神的方法是定义您自己的 begin_with 算法。
这为客户端代码提供了更简单的接口,并且与大多数标准库容器兼容。
An approach that might be more in keeping with the spirit of the Standard Library would be to define your own begins_with algorithm.
This provides a simpler interface to client code and is compatible with most Standard Library containers.
查看 Boost 的 String Algo 库,它有一个许多有用的函数,例如starts_with、istart_with(不区分大小写)等。如果您只想在项目中使用部分boost库,那么您可以使用bcp实用程序仅复制所需的文件
Look to the Boost's String Algo library, that has a number of useful functions, such as starts_with, istart_with (case insensitive), etc. If you want to use only part of boost libraries in your project, then you can use bcp utility to copy only needed files
看来 std::string::starts_with 在 C++20 内部,同时 std::string::find 可以使用
It seems that std::string::starts_with is inside C++20, meanwhile std::string::find can be used
我觉得我没有完全理解你的问题。 看起来它应该是微不足道的:
这只查看(最多)前三个字符。 编译时未知的字符串的泛化需要您用循环替换上面的内容:
I feel I'm not fully understanding your question. It looks as though it should be trivial:
This only looks at (at most) the first three characters. The generalisation for a string which is unknown at compile time would require you to replace the above with a loop: