如何在字符串输入中查找模式?

时间:2018-08-11 12:53:28

标签: c++ string

我如何解析一个看起来像“ xxxx-xxxx”的字符串,并将那些 xxxx 部分作为一个数字?例如,用户将键入“ 9349-2341”,我将得到两个不同整数的数字。

对于随机数生成器,我需要这样做,它会在这些xxxx变量之间选择数字。

谢谢。

3 个答案:

答案 0 :(得分:4)

您可以使用std::stringstream从字符串中提取数字。看起来像这样:

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];

还有C函数,例如sscanf()。例如,可以使用以下格式提取模式:"%d-%d"

答案 1 :(得分:2)

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);

//在n1n2之间进行随机数生成

答案 2 :(得分:0)

使用正则表达式

如果您输入的内容确信类似“ xxxx-xxxx”(其中“ x”代表数字),则只需使用以下功能即可:

#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;
}

关于如何将字符串转换为数字,请查看this article,并引述以下段:

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 

或者,如下所示:

使用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;
}

您应该查看C ++参考网站,例如CPlusPlus

相关问题