How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?(如何检查 C++ std::string 是否以某个字符串开头,并将子字符串转换为 int?)
问题描述
如何在 C++ 中实现以下(Python 伪代码)?
How do I implement the following (Python pseudocode) in C++?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果 argv[1] 是 --foo=98,则 foo_value 是 98>.)
(For example, if argv[1] is --foo=98, then foo_value is 98.)
更新:我对研究 Boost 犹豫不决,因为我只是想对一个简单的小命令行工具进行很小的更改(我宁愿不必学习如何链接并使用 Boost 进行微小更改).
Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool (I'd rather not have to learn how to link in and use Boost for a minor change).
推荐答案
使用 rfind 重载,采用搜索位置 pos 参数,并为其传递零:
Use rfind overload that takes the search position pos parameter, and pass zero for it:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}
谁还需要什么?纯 STL!
Who needs anything else? Pure STL!
许多人误读了这意味着在整个字符串中向后搜索以查找前缀".这将给出错误的结果(例如 string("tititito").rfind("titi") 返回 2,因此当与 ==0 相比时将返回 false)它会效率低下(查看整个字符串,而不仅仅是开头).但它不会这样做,因为它将 pos 参数作为 0 传递,这将搜索限制为仅在该位置或更早匹配.例如:
Many have misread this to mean "search backwards through the whole string looking for the prefix". That would give the wrong result (e.g. string("tititito").rfind("titi") returns 2 so when compared against == 0 would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the pos parameter as 0, which limits the search to only match at that position or earlier. For example:
std::string test = "0123123";
size_t match1 = test.rfind("123"); // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)
这篇关于如何检查 C++ std::string 是否以某个字符串开头,并将子字符串转换为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查 C++ std::string 是否以某个字符串开头,并
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
