首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查C++ std::string是否以某个字符串开头,并将子字符串转换为整型?

如何检查C++ std::string是否以某个字符串开头,并将子字符串转换为整型?
EN

Stack Overflow用户
提问于 2009-12-10 08:57:27
回答 22查看 393.2K关注 0票数 338

如何在C++中实现以下代码(Python伪代码)?

if argv[1].startswith('--foo='):
    foo_value = int(argv[1][len('--foo='):])

(例如,如果argv[1]--foo=98,则foo_value98。)

我对Boost犹豫不决,因为我只是在考虑对一个简单的小命令行工具进行非常小的更改(我宁愿不必学习如何链接和使用Boost来进行小更改)。

EN

回答 22

Stack Overflow用户

回答已采纳

发布于 2016-11-06 01:36:09

使用带有搜索位置pos参数的rfind重载,并为其传递零:

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
  // s starts with prefix
}

还需要别的什么吗?纯STL!

许多人将其误读为“在整个字符串中反向搜索前缀”。这将给出错误的结果(例如,string("tititito").rfind("titi")返回2,因此与== 0相比将返回false),而且效率将很低(查看整个字符串,而不仅仅是开始部分)。但它没有这样做,因为它将pos参数作为0传递,这将搜索限制为仅在该位置或更早的位置匹配。例如:

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)
票数 675
EN

Stack Overflow用户

发布于 2009-12-10 09:07:31

你可以这样做:

std::string prefix("--foo=");
if (!arg.compare(0, prefix.size(), prefix))
    foo_value = std::stoi(arg.substr(prefix.size()));

寻找像Boost.ProgramOptions这样的库来为您做这件事也是一个好主意。

票数 200
EN

Stack Overflow用户

发布于 2009-12-10 09:03:42

如果你已经在使用Boost,你可以使用boost string algorithms + boost lexical cast:来完成

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter
}

这种方法,就像这里提供的许多其他答案一样,对于非常简单的任务是可以的,但从长远来看,使用命令行解析库通常会更好。Boost有一个(Boost.Program_options),如果你碰巧已经在使用Boost,这可能是有意义的。

否则,搜索"c++命令行解析器“将会出现许多选项。

票数 92
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1878001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档