获取字符串的长度(以C++为单位)
Getting the length of a string in C++
int strStr(string haystack, string needle) {
int i, j;
for(i = 0; i <= haystack.length() - needle.length(); i++){
for(j = 0; j < needle.length(); j++){
if(haystack[i+j] != needle[j]){
break;
}
}
if(j == needle.length()){
return i;
}
}
return -1;
}
这是我为实现 strStr 函数而编写的代码。我发现很奇怪,当 haystack = " 和 needle = "a" 时,它返回的结果是 32 而不是 -1。
但是,当我将第三行修改为
int k = haystack.length() - needle.length();
for(i = 0; i <= k; i++){
它返回正确的输出 -1。现在我真的很困惑。为什么我最初编写的代码是错误的?它们之间有什么区别?
使用:
int(haystack.length()) - int(needle.length())
请注意
cout<<(size_t(0)-size_t(1))<<endl;
显示
18446744073709551615
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 正向声明的枚举,默认值以.h为单位
- 常量"C"占用的空间(以字节为单位)