How to extract number before a symbol in C++

Viewed 206

I have tried Googling but just can't find my answer.

I have a string "0-9". I want to extract the number before and after the dash and store it in a variable

e.g
string A = "0-9";
output:
min = 0
max = 9

I managed to get the number after dash but not before.

string str = "0-9";
string max = str.substr(str.find("-") + 1);
cout << max;

It should work for "10-20" also.

5 Answers
     auto dashPos = A.find('-');
     auto before = A.substr(0,dashPos);
     auto after = A.substr(dashPos + 1);
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <iostream>

int main() {
    int min, max;
    std::string s = "0-9";
    sscanf(s.data(), "%d-%d", &min, &max);
    std::cout << min << ", " << max;
}

Personally, I find this operator very handy:

#include <iostream>
#include <cctype>

std::istream& operator>>(std::istream& is, char const* s) {

        if (is.flags() & std::ios::skipws) {
                while (std::isspace(is.peek()))
                        is.ignore(1);

                while (std::isspace((unsigned char)* s))
                        ++s;
        }

        while (*s && is.peek() == *s) {
                is.ignore(1);
                ++s;
        }
        if (*s)
                is.setstate(std::ios::failbit);
        return is;
}

This lets you "read" a string literal from an input stream. In doing so, it reads input from the stream and matches it against the literal you pass. If they don't match, it set the stream's failbit. If they do match, it consumes that matching data from the stream.

I think that sounds more complicated than it really is. In real use, you'd do something like this:

std::istringstream input{"10-29"};

int min;
int max;

input >> min >> "-" >> max; // min = 10, max=29

This also recognizes the stream's skipws flag. If that's set (which it usually is) it skips white space before trying to read the delimiter you've specified, so input like 1 - 20 would work as well.

I actually like a regex solution to this one. It's pretty simple and actually uses the prefix and suffix properties of the match_results.

#include <string>
#include <iostream>
#include <regex>
int main(int argc, char * argv[]){
    std::string A = "0-9";
    std::cmatch cm;
    std::regex_search(A.c_str(), cm, std::regex("-"));
    int nums[2]{ std::stoi(cm.prefix()), std::stoi(cm.suffix()) };
    for (auto i : nums) {
        std::cout << i << '\n';
    }
    return 0;
}
Related