C++ .length() 函数给出错误的结果

标签 c++ string

我分析字符串的代码打印的整数位置数不正确。 结果最初相差 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/

相关文章:

c++ - 使用 libgit2 从另一个分支创建新的 git 存储库?

c++ - 如何使用无范围枚举器,就好像它的类型是它的基础类型一样

c++ - makefile 没有这样的文件或目录 : libxml/xmlstring. h

c++ - 通过指针排序

C++:从堆栈内存返回 std::string 引用

c# - 如何在不丢失其在 C# 中的部分的情况下真正将字符串拆分为字符串数组?

java - 忽略字符串中的数字

c - 从C文件中读取字符串的问题

PHP - 向字符串添加空字符

C++ 使用标准 :string v char* in a base class - base class has a redudant copy of the string