我如何在c++中实现以下(Python伪代码)?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果argv[1]是——foo=98,那么foo_value是98。)
更新:我很犹豫是否要研究Boost,因为我只是想对一个简单的小命令行工具做一个非常小的改变(我宁愿不学习如何链接并使用Boost进行一个小的改变)。
我如何在c++中实现以下(Python伪代码)?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(例如,如果argv[1]是——foo=98,那么foo_value是98。)
更新:我很犹豫是否要研究Boost,因为我只是想对一个简单的小命令行工具做一个非常小的改变(我宁愿不学习如何链接并使用Boost进行一个小的改变)。
当前回答
在c++ 20中,starts_with作为std::string的成员函数可用,定义为:
constexpr bool starts_with(string_view sv) const noexcept;
constexpr bool starts_with(CharT c) const noexcept;
constexpr bool starts_with(const CharT* s) const;
所以你的代码可以是这样的:
std::string s{argv[1]};
if (s.starts_with("--foo="))
其他回答
好的,为什么要复杂地使用库之类的东西?c++字符串对象重载[]操作符,所以你可以只比较字符。就像我刚才做的,因为我想列出目录中的所有文件忽略不可见文件和。和。pseudofiles。
while ((ep = readdir(dp)))
{
string s(ep->d_name);
if (!(s[0] == '.')) // Omit invisible files and .. or .
files.push_back(s);
}
就是这么简单。
从c++ 20开始,你可以使用starts_with方法。
std::string s = "abcd";
if (s.starts_with("abc")) {
...
}
std::string text = "--foo=98";
std::string start = "--foo=";
if (text.find(start) == 0)
{
int n = stoi(text.substr(start.length()));
std::cout << n << std::endl;
}
在c++ 11或更高版本中,可以使用find()和find_first_of()
使用find查找单个char的示例:
#include <string>
std::string name = "Aaah";
size_t found_index = name.find('a');
if (found_index != std::string::npos) {
// Found string containing 'a'
}
示例使用find查找完整字符串并从位置5开始:
std::string name = "Aaah";
size_t found_index = name.find('h', 3);
if (found_index != std::string::npos) {
// Found string containing 'h'
}
使用find_first_of()方法只搜索第一个字符,只搜索起始点:
std::string name = ".hidden._di.r";
size_t found_index = name.find_first_of('.');
if (found_index == 0) {
// Found '.' at first position in string
}
更多关于find 关于find_first_of的更多信息
好运!
text.substr(0, start.length()) == start