If I have a string where there is some word and some number (like "Text 125"), is it possible to get this number and convert it to int without using regex?
2 Answers
Yes, you could use a stringstream if you know that it's a word followed by a number.
std::stringstream ss("Text 125");
std::string buffer; //a buffer to read "Text" into
int n; //to store the number in
ss >> buffer >> n; //reads "Text" into buffer and puts the number in n
std::cout << n << "\n";
Edit: I found a way to do it without needing to declare a pointless variable. It's a bit less robust though. This version assumes that there is nothing after the number. std::stoi will work regardless of the number of spaces between the word and the number.
std::string str("Text 125");
int n = std::stoi(str.substr(str.find_first_of(' ') + 1));
std::cout << n << std::endl;
1 Comment
If you know exactly the format of the expected string, i.e. that it
- always starts with "Text"
- followed by a space
- followed by a number
- and then ends
- (so in regex terms, it's
/^Text (\d+)$/)
you can combine std::find and std::substr.
const std::string inputStr = "Text 125";
const std::string textStr = "Text ";
const std::size_t textPos = inputStr.find(textStr);
const std::size_t numberPos = textPos + textStr.length();
const std::string numberStr = inputStr.substr(numberPos);
const int numberInt = std::atoi(numberStr.c_str());
However, that only works in these specific circumstances. And even if /^Text (\d+)$/ is the only expected format, other input strings might still be possible, so you'll need to add the appropriate length checks, and then either throw an exception or return an invalid number or whatever you need to happen for invalid input strings.
@DanielGiger's answer is more generally applicable. (It only requires the number to be the second string, covering the more general case of /^\S+\s+(\d+)/)