目录
1.查找字符串|判断包含关系
string.find()与string::npos
查找字符串a是否包含子串b,不是用strA.find(strB) > 0 而是 strA.find(strB) != string:npos
if(
strA.find(strB) == string::npos )//不存在。
if(
strA.find(strB) != string::npos )//存在。
注意:
错误1:
int idx = str.find("abc");
if (idx == string::npos)
...
上述代码中,idx的类型被定义为int,这是错误的,即使定义为 unsigned int 也是错的,它必须定义为 string::size_type。
npos 是这样定义的:
static const size_type npos = -1;
因为 string::size_type (由字符串配置器 allocator 定义) 描述的是 size,故需为无符号整数型别。因为缺省配置器以型别 size_t 作为 size_type,于是 -1 被转换为无符号整数型别,npos 也就成了该型别的最大无符号值。不过实际数值还是取决于型别 size_type 的实际定义。不幸的是这些最大值都不相同。事实上,(unsigned long)-1 和 (unsigned short)-1 不同(前提是两者型别大小不同)。因此,比较式 idx == string::npos 中,如果 idx 的值为-1,由于 idx 和字符串string::npos 型别不同,比较结果可能得到 false。
错误2:if(str.find("abc") )
注:找不到abc会返回-1,不为0为True。0为False
通常来说,find函数用于寻找某个序列的在string中第一次出现的位置。
原文链接:https://blog.youkuaiyun.com/qq_33933704/article/details/79188028
2.std::cerr与std::cout区别
std::cerr(console error)是ISO C++标准错误输出流,对应于ISO C标准库的stderr。
cerr对应标准错误流,用于显示错误消息。默认情况下被关联到标准输出流,但它不被缓冲,也就说错误消息可以直接发送到显示器,而无需等到缓冲区或者新的换行符时,才被显示。一般情况下不被重定向。
例如下面代码编译后生成test.exe
// test.