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

C++ .length() function giving wrong results

本文关键字:出错 错误 结果 函数 length C++      更新时间:2023-10-16

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

希望这有帮助!

相关文章: