【问题标题】:String find function in C++ returns 0 if string passed as argument is empty如果作为参数传递的字符串为空,则 C++ 中的字符串查找函数返回 0
【发布时间】:2021-02-02 17:46:33
【问题描述】:


当一个空字符串被传递给 find 函数时,它返回 0。
如果传递了未初始化的字符串,那么它也返回0。

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

int main() {
    string str1="";
    string str2="This is a sample string";
    unsigned int loc = str2.find(str1);
    cout << "Loc : " << loc << endl;
    if(loc != string::npos)
    {
        cout << "Found" << endl;
    }
    else
    {
        cout << "Not found" << endl;
    }
    return 0;
}

输出
位置 : 0
找到

我的问题是为什么 find 返回 0 而不是返回 string::npos ?

【问题讨论】:

  • 对于记录,空字符串相当于一个未初始化的。
  • string str1; str1 初始化后;默认构造函数用于初始化字符串,恰好将其初始化为空字符串。获得未初始化的字符串相当困难。你需要跳一些圈才能得到一个未初始化的字符串:void* memory = std::malloc(sizeof(std::string)); std::string* uninitializedStringPointer = static_cast&lt;std::string*&gt;(memory);

标签: c++ stdstring


【解决方案1】:

如果i + len(l) &lt;= len(h) 和所有0 &lt;= k &lt; len(l) 我们有l[k] == h[i+k],则可以在干草堆hi 位置找到针l。您正在处理的只是此定义的vacuous truth:如果没有有效的 x 开头,'for all x' 将自动变为 true。

【讨论】:

    【解决方案2】:

    正如docs on cppreference 所说。 (重点是我的。)

    查找与给定字符序列相等的 first 子字符串。搜索从 pos 开始,即找到的子字符串不能从 pos 之前的位置开始。

    1. 找到第一个等于str的子字符串。

    什么时候在某个位置找到字符串?

    形式上,如果以下所有条件都为真,则称在位置 xpos 处找到子字符串 str:

    • xpos &gt;= pos
    • xpos + str.size() &lt;= size()
    • 对于所有职位nstr, Traits::eq(at(xpos+n), str.at(n))

    空字符串在位置 0 处满足这些要求。

    文档进一步说。 (重点是我的。)

    特别是,这意味着

    • 只有当pos &lt;= size() - str.size() 时才能找到子字符串
    • 当且仅当 pos &lt;= size() 时才会在 pos 找到空子字符串
    • 对于非空子字符串,如果pos &gt;= size(),函数总是返回npos

    【讨论】:

    • 它没有明确提及,尽管“对于 str 中的所有位置 n,Traits::eq(at(xpos+n), str.at(n))”意味着可以找到一个空子字符串任何地方,因为它的大小为 0,因此对于子字符串中的任何位置来说,任何东西都是正确的
    • @largest_prime_is_463035818 文档说find 找到了 first 子字符串。
    【解决方案3】:

    它在位置 0(第一个搜索到的)找到完全匹配,因此返回索引。

    引用cppreference,条件为:

    如果满足以下所有条件,则称在位置xpos 处找到子字符串str

    1. xpos &gt;= pos
    2. xpos + str.size() &lt;= size()
    3. 对于所有职位nstr, Traits::eq(at(xpos+n), str.at(n))

    尝试从位置 0 匹配子字符串,我们得到了

    1. 满足,因为 0(我们的搜索位置)>= 0(开始参数)
    2. 满足,因为 0 + 0
    3. 满足,因为针中没有字符与 haystack 中的对应字符不匹配 - 全部匹配。

    【讨论】:

      猜你喜欢
      • 2018-03-14
      • 2014-05-09
      • 2021-11-30
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2017-04-25
      • 2012-11-15
      • 1970-01-01
      相关资源
      最近更新 更多