开发者

Need to extract last figure after dot in a string like "7.8.9.1.5.1.100"

开发者 https://www.devze.com 2023-02-09 01:04 出处:网络
I need to extract last number after last dot in a C++ string like \"7.8.9.1.5.1.100\" and store it in an integer??

I need to extract last number after last dot in a C++ string like "7.8.9.1.5.1.100" and store it in an integer??

Added: This string could also 开发者_高级运维be "7.8.9.1.5.1.1" or "7.8.9.1.5.1.0".

I would also like to validate that that its is exactly "7.8.9.1.5.1" before last dot.


std::string has a rfind() method; that will give you the last . From there it's a simple substr() to get the string "100".


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());
}


Using C++0x regex (or boost::regex) check your string against a basic_regex constructed from the string literal "^7\\.8\\.9\\.1\\.5\\.1\\.(?[^.]*\\.)*(\d+)$". The capture group $1 will be useful.


with the updated information, the code below should do the trick.

#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;
}

EDIT: updated to skip cases where there are more dots after the match, atoi would have still parsed and returned the value up to the ..

0

精彩评论

暂无评论...
验证码 换一张
取 消