Search code examples
c++text-extraction

How to extract number before a symbol in C++


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.


Solution

  • https://www.cplusplus.com/reference/string/string/substr/

    string substr (size_t pos = 0, size_t len = npos) const;

    string str = "0-9";
    string min = str.substr(0, str.find("-"));
    cout << min;