Ferit Yiğit BALABAN
Ferit Yiğit BALABAN

Reputation: 105

How to look up a pattern in string input?

How can I parse a string that looks like "xxxx-xxxx" and get those xxxx parts as a number? For an example, the user will type in "9349-2341" and I will get those numbers as two different integers.

I need to do that for a random number generator, which chooses the number between these xxxx variables.

Thanks.

Upvotes: 1

Views: 129

Answers (3)

KaiserKatze
KaiserKatze

Reputation: 1569

Using regular expression

If your input is assured to resemble "xxxx-xxxx" where 'x' represents a digit, you can simply ultilize the following function:

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main()
{
    string input = "9349-2341";

    // This pattern matches any string begining with 4 digits and ending with 4 digits, both parts seperated by a slash
    string pattern = "([0-9]{4})-[0-9]{4}";
    smatch matcher;

    regex prog (pattern);

    if (regex_search(input, matcher, prog))
    {
        auto x = matcher[1];
        cout << x << " " << endl;
        input = matcher.suffix().str();
    }
    else
    {
        cout << "Invalid input!" << endl;
    }

    return 0;
}

As for how to convert string to number, check out this article, from which the following segment is quoted:

string Text = "456";//string containing the number
int Result;//number which will contain the result

stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Text

if ( !(convert >> Result) )//give the value to Result using the characters in the string
    Result = 0;//if that fails set Result to 0
//Result now equal to 456 

Or, simply as followed:

Using sscanf

#include <cstdio>

using namespace std;

int main(int argc, char ** argv)
{
    char input[] = "1234-5678";
    int result, suffix;

    sscanf(input, "%i-%i", &result, &suffix);

    printf("Output: '%i-%i'.\n", result, suffix);

    return 0;
}

You should check out C++ reference websites, such as CPlusPlus.

Upvotes: 1

tofu head
tofu head

Reputation: 119

std::string str = "1234-5678";

std::string str1 = str.substr (0,4); 
std::string str2 = str.substr(5, 4);

int n1 = std::stoi(str1);
int n2 = std::stoi(str2);

// do your random number generation between n1 and n2

Upvotes: 2

Shorrer
Shorrer

Reputation: 104

You can use std::stringstream to extract numbers from string. It looks like that:

std::stringstream str_stream;
std::string str_to_parse = "1234-5678";
int num[2];

str_stream << str_to_parse;
str_stream >> num[0];
str_stream.ignore(1); // otherwise it will extract negative number (-5678)
str_stream >> num[1];

Also, there is C functions, like sscanf(). For example, your pattern can be extracted with this format: "%d-%d".

Upvotes: 4

Related Questions