查找字符串是否包含字符串,并处理附加的数字

Finding if a string contains a string and manipulating attached numbers

本文关键字:字符串 数字 处理 是否 包含 查找      更新时间:2023-10-16

假设作为输入的一部分,一个用户输入nrt:x来告诉程序计算x的第n个根。如果我想把n和x发送到另一个方法来简化第n个根号,我想我可以使用std::string::find来查找"rt:"。如果find返回true,那么我需要将n和x发送到另一个方法,但在找到"rt:"之后,我该怎么做呢?例如,用户输入7rt:3。对于"rt:",Find将返回true,然后我如何将3和7发送到另一个方法?

if(std::string::find(rt:)) {
    //manipulate numbers before/after rt: from user input
    if(result will be an int) {
        nthRoot(double n, double x);
    }
    If(result will not be an int) {
        nthRootSimplify(double n, double x);
    }
}
void nthRoot(double x, double n){
    double nthRootSol = pow(x, double(1 / n));
}

编辑:在你的帮助下,我写的代码是一个解决方案。任何建议都很好。如果"n"或"z"大于1 int,我会发现自己遇到了问题。

void findNthRoot(string x) {
if(x.find("rt:") != string::npos) {
    unsigned position = x.find("rt:");
    cout << position << endl;
    double n = position - 1;
    cout << n << endl;
    double z = position + 3;
    cout << z << endl;
    string str1 = x.substr(n, 1);
    string str2 = x.substr(z);
    cout << str1 << endl;
    cout << str2 << endl;
}
}
int main()  {
    findNthRoot("2 - 1+3rt:4");
    return 0;
}

输出为:7.6.103.4.最重要的是"3"answers"4"是str1和str2 的值

如果假设输入总是以n开头,以部首下的数字结尾,则可以使用std::string::front()访问第一个元素,使用std::string::back()访问最后一个元素。

find返回true。这样的find是非常无用的。实际的std::string::find返回找到的字符串的位置

知道了位置,现在可以使用std::string::substr将字符串分为"之前"answers"之后"部分。