【发布时间】: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<std::string*>(memory);