You need to extract the last digit after the dot in the line, for example, "7.8.9.1.5.1.100"

I need to extract the last number after the last dot in a C ++ line, for example "7.8.9.1.5.1.100", and store it as an integer

Added: This line can also be "7.8.9.1.5.1.1" or "7.8.9.1.5.1.0".

I would also like to confirm that this is exactly "7.8.9.1.5.1" to the last point.

+6
c ++ string
source share
4 answers

std::string has an rfind() method; which will give you the last . From there it is just substr() to get the string "100" .

+6
source share
 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()); } 
+3
source share

Using the C ++ 0x regular expression (or boost::regex ) checks your string for basic_regex , built from the string literal "^7\\.8\\.9\\.1\\.5\\.1\\.(?[^.]*\\.)*(\d+)$" . A $1 capture group will be helpful.

+1
source share

with 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 points left after the match, atoi would still analyze and return the value to . .

+1
source share

All Articles