需要提取像“7.8.9.1.5.1.100”字符串中的点后的最后一个数字

问题描述:

我需要在诸如“7.8.9.1.5.1.100”之类的C++字符串中的最后一个点之后提取最后一个数字并将其存储在一个整数?需要提取像“7.8.9.1.5.1.100”字符串中的点后的最后一个数字

加: 该字符串也可以是“7.8.9.1.5.1.1”或“7.8.9.1.5.1.0”。

我也想验证它的确是最后一个点之前的“7.8.9.1.5.1”。

std::string有一个rfind()方法;那会给你最后的.从那里得到一个简单的substr()得到字符串"100"

+0

并使用atoi从字符串中获取整数。 – 2011-02-08 12:32:22

+3

@Benoit Thierry:我宁愿使用`stoi`或者`lexical_cast`。 – 2011-02-08 12:54:51

+0

你是不是指`strtol`?这是`atoi`的标准选择。 – MSalters 2011-02-08 13:00:48

const std::string s("7.8.9.1.5.1.100"); 
const size_t i = s.find_last_of("."); 
if(i != std::string::npos) 
{ 
    int a = boost::lexical_cast<int>(s.substr(i+1).c_str()); 
} 

使用的C++ 0x正则表达式(或boost::regex)检查字符串针对来自字符串文字"^7\\.8\\.9\\.1\\.5\\.1\\.(?[^.]*\\.)*(\d+)$"构造的basic_regex。捕获组$1将很有用。

随着更新的信息,下面的代码应该做的伎俩。

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <cstdlib> 

int main(void) 
{ 
    std::string base("7.8.9.1.5.1."); 
    std::string check("7.8.9.1.5.1.100"); 
    if (std::equal(base.begin(), base.end(), check.begin()) && check.find('.', base.size()) == std::string::npos) 
    { 
    std::cout << "val:" << std::atoi(check.c_str() + base.size()) << std::endl; 
    } 
    return 0; 
} 

编辑:更新跳过那里有比赛结束后多个点的情况下,atoi会仍然分析和返回的值到.