【问题标题】:Function find() works incorrect函数 find() 工作不正确
【发布时间】:2021-12-02 04:23:15
【问题描述】:

我的任务是检查一个数字是否包含8。我已将数字转换为std::string 并使用了它的find() 方法。但它只适用于以8 开头的数字,例如881881 等。对于1828 等数字,它不起作用。

#include <iostream>
#include <math.h>
#include <string>

using namespace std;

unsigned long long g = 0;


int main()
{
    string str;
    cin >> str;
    int f = stoi(str);
    string eig = "8";
    for (int a = 1; a <= f; a++)
    {
        string b = to_string(a);
        if (b.find(eig) != size_t() && b.rfind(eig) != size_t())
        {
            cout << "It worked with " << b << "\n";
            g++;
        }
        
    }
    cout << g;
}

【问题讨论】:

  • 请阅读How to Askminimal reproducible example。我们需要查看您的代码。
  • 对不起,我只要求我的一段代码。我的代码解决了另一个任务,但我只需要 find() 函数的答案
  • std::string::find - "...找到的子字符串的第一个字符的位置,如果没有找到这样的子字符串,则为 npos..." i> en.cppreference.com/w/cpp/string/basic_string/find
  • minimal reproducible example (MRE) 的一个很酷的事情是它是一些强大的调试技术的提炼,并且制作 MRE 通常会在发现和修复错误的情况下提前结束,而无需来自我们。如果您提出问题而您还没有 MRE 或类似的东西,那么您就是在伤害自己。

标签: c++ string find


【解决方案1】:

您错误地使用了std::string::find()std::string::rfind()。如果未找到匹配项,它们不会返回 size_t()。他们改为返回std::string::npos(即size_type(-1))。 size_t() 的值为 0,因此如果根本没有找到匹配项 (-1 != 0),或者匹配第一个字符以外的任何字符 (@987654329),find(...) != size_t() 将评估为真@)。这不是你想要的。

另外,您对rfind() 的使用是多余的,因为如果find() 找到匹配项,那么rfind() 肯定也会找到匹配项(尽管不一定是 same 匹配项,但您并没有试图区分这一点)。

试试这个:

#include <iostream>
#include <string>
using namespace std;

unsigned long long g = 0;

int main()
{
    int f;
    cin >> f;
    for (int a = 1; a <= f; a++)
    {
        string b = to_string(a);
        if (b.find('8') != string::npos)
        {
            cout << "It worked with " << b << "\n";
            ++g;
        }        
    }
    cout << g;
}

【讨论】:

    【解决方案2】:
    #include <iostream>
    #include <string>
    #include <cassert>
    
    int main(int argc, char **argv) {
        auto s = std::to_string(1234567890);
        assert(s.find('8') != std::string::npos);
        return 0;
    }
    

    这是你想要的吗?

    【讨论】:

    • 我知道你要去哪里,但提问者和追随者可能看不到。请简要说明您的解决方案及其工作原理。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2016-01-14
    • 2012-08-07
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    相关资源
    最近更新 更多