如何检查是否一个C ++< string>以某个字符串开始,并将子字符串转换为int? [英] How do I check if a C++ <string> starts with a certain string, and convert a substring to an int?
本文介绍了如何检查是否一个C ++< string>以某个字符串开始,并将子字符串转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C ++中执行以下操作(Python伪代码)
How do I do 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.)
strong> Update:我很想看看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.)
推荐答案
使用 boost字符串算法 + 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库一样,字符串算法&词法转换是标题,没有任何链接。
Like most boost libraries, string algorithm & lexical cast are header-only, there's nothing to link in.
这篇关于如何检查是否一个C ++< string>以某个字符串开始,并将子字符串转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文