如何检查C ++ std :: string是否以某个字符串开头,并将子字符串转换为int? [英] How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

查看:2359
本文介绍了如何检查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_value98.)

(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参数.在这里,pos是最后一个被视为搜索主题一部分的索引(因此,如果您的字符串为titititi,则不考虑后者titi,因为它的开始时间晚于所选的pos=0)):

Use an overload of rfind which has the pos parameter. Here, pos is the last index to be considered part of the search subject (so, if your string would be titititi, the latter titi is not considered because it starts later than the chosen pos=0):

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

谁还需要其他东西?纯STL!

Who needs anything else? Pure STL!

这篇关于如何检查C ++ std :: string是否以某个字符串开头,并将子字符串转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆