C++ .length() 函数给出错误的结果
C++ .length() function giving wrong results
我分析字符串的代码在整数中打印的位置数不正确。结果最初偏差 1 个整数,当我在字符串中插入一个 char 时,即使我只添加一个 char,结果也会更改 2 个位置值。这是代码:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(){
string s1 = "Hey, what's up?";
cout << s1.length() << endl; // should be 14 positions, not 15 if starting at 0
cout << s1.insert(1, "k") << endl;
s1 = s1.insert(1, "k");
cout << s1.length() << endl; //should be 15, not 17
system("pause");
return 0;
}
请告诉我为什么.length()
没有打印正确的位置数。
.length()
不返回字符串的结束位置,它返回字符串中的元素数。"四"将是 4,因为它有四个字母。
std::string four = "four";
std::cout << four.length() << std::endl;
输出:
4
第二部分的返回值是 17 而不是 16 的原因是,您插入了 k 两次,一次在 std::cout 中,第二次在代码中。您的实际输出字符串将是这样的:
Hkkey, what's up?
string::length()
返回字符串中的字符数,而不是最后一个字符的位置,因此15
是正确的。
一想:如果空字符串像您想象的那样返回最后一个字符的位置length()
会返回什么?
string::length
返回字符数,这与位置数不同。 字符数是您在开始时开始并为每个字符增加一个计数器时要计算的数量,因此它不应该出现在最后一个位置的索引中。 有效指数的范围是[0, str.length() - 1]
,其中包括str.length()
仓位。
希望这有帮助!
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 编译类 C++ 中的线程时出错(错误 xthread)
- 加载GLEW库时出错(错误LNK2001)
- 通过函数指针调用函数时出错(错误C2064)
- 编译core.obj时出错:错误LNK2001:未解析的外部符号_harmony_core_init
- 链接c++静态库与android ndk时出错(错误:无法识别文件格式)
- 使用GCC编译游戏时出错.(错误:将"Screen"的含义从"class Screen&q