![](/img/trans.png)
[英]What is the difference between const string & str and string const & str when passed as an argument to a function in c++
[英]String find function in C++ returns 0 if string passed as argument is empty
当传递一个空字符串来查找 function 时,它返回 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;
}
Output :
地点:0
成立
我的问题是为什么 find 返回 0 而不是返回 string::npos?
如果i
i + len(l) <= len(h)
l
h
所有0 <= k < len(l)
我们有l[k] == h[i+k]
. 你所处理的只是这个定义的空洞事实:如果没有有效的x开头,'for all x ' 会自动变为 true。
正如cppreference 上的文档所说。 (重点是我的。)
查找与给定字符序列相等的第一个substring。 搜索从 pos 开始,即找到的 substring 不能从 pos 之前的 position 开始。
- 找到第一个 substring 等于
str
。
何时在 position 中找到字符串?
形式上,如果以下所有条件都为真,则可以在 position xpos 找到 substring str:
xpos >= pos
xpos + str.size() <= size()
- 对于
str
中的所有位置n
,Traits::eq(at(xpos+n), str.at(n))
空字符串在 position 0 处满足这些要求。
文档进一步说。 (重点是我的。)
特别是,这意味着
- 仅当
pos <= size() - str.size()
时才能找到 substring- 当且仅当
pos
pos <= size()
- 对于非空 substring,如果
pos >= size()
,则 function 始终返回npos
。
它在 position 0(搜索到的第一个)处找到完全匹配,因此返回索引。
引用cppreference ,条件是:
形式上,如果以下所有条件都为真,则可以在 position
xpos
找到 substringstr
:
xpos >= pos
xpos + str.size() <= size()
- 对于
str
中的所有位置n
,Traits::eq(at(xpos+n), str.at(n))
尝试从 position 0 匹配 substring,我们得到了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.