c++ - 为什么 std::string::find() 可以处理 '\0' ?

标签 c++ c c++11

strstr()std::string::find() 的实现有什么区别?

例如:

char* str = "abc\0hijk@#$%";
char* temp;
std::string str1;

for (int i=0; i <=12; i++) {
    str1.push_back(str[i]);
}

strstr(temp, "@#");// can not handle'\0' 
str1.find("@#");// success

最佳答案

std::string class 是一个 C++ 类,表示可以包含空字符的字符串。它的成员函数(例如 find)旨在处理这些嵌入的空值。

strstr (来自 C 的函数)使用 char* 指针,该指针指向 C 样式字符串。由于 C 样式字符串以 null 结尾,因此它们无法处理嵌入的 null。为此,strstr 记录如下:

Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.

The matching process does not include the terminating null-characters, but it stops there.

斜体部分与此处相关。

关于c++ - 为什么 std::string::find() 可以处理 '\0' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61412956/

相关文章:

c++ - 如何识别项目是托管c++项目还是非托管c++项目

c++ - 什么时候初始化匿名命名空间数据?

c++ - 递归替换子字符串的最快算法

php - 使用 mcrypt 在 php 和 c 中进行 AES 加密

c++ - gsl_histogram : Value being equal to an edge between two bins, 值会分配给哪个bin?

c++ - 在 map 中插入数组元素的时间复杂度是多少?

c++ - 如何在编译时通过名称/指针获取模板参数默认值的函数类型?

c++ - 如何在 C++ 中将日期时间格式从 yyyy-MM-dd 转换为 yyyy/MM/dd?

c - GCC/命令提示符错误 : '.' is not recognized as an internal or external command

c++ - 通过写入外部变量来取消 C++ 线程是否安全/有效?