我分析字符串的代码打印的整数位置数不正确。 结果最初相差 1 个整数,当我向字符串中插入一个字符时,即使我只添加了一个字符,结果也会改变 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()
不返回字符串的结束位置,它返回字符串中元素的个数。 IE。 “四”将是 4,因为它有四个字母。
std::string four = "four";
std::cout << four.length() << std::endl;
输出:
4
第二部分的返回值为 17 而不是 16 的原因是因为您插入了两次 k,一次是在您的 std::cout 中,第二次是在稍后的代码中。您的实际输出字符串将是这样的:
Hkkey, what's up?
关于C++ .length() 函数给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19352449/