gpt4 book ai didi

c++ - 在 C++ 中,如何比较字符数组与字符串的大小?

转载 作者:太空狗 更新时间:2023-10-29 19:41:45 24 4
gpt4 key购买 nike

我有以下声明

char c[] = "Hello";
string c2 = "Hello";

我想比较 a) 需要多少字节的内存和 b) 字符长度。我知道字符数组会在字符串末尾添加一个空终止符,而字符串数据类型则不会。

使用

cout << "The sizeof of c: " << sizeof(c);
cout << "The sizeof of c2: " << sizeof(c2);

返回 6 和 4,我不确定为什么是 4 而不是 5?还有这里的长度函数如何比较...

当我使用下面的代码时

cout << "The sizeof of c: " << sizeof(c);
cout <<"The sizeof of c2: " << c2.length();

我得到 6 和 5 ...但它是否以相同的方式比较长度?谢谢。

最佳答案

a) how many bites of memory both need and

您正确地使用了 sizeof 运算符来确定字符数组占用的字节数。

sizeof( c )

对于std::string类型的对象,则占用两 block 内存。第一个用于分配对象本身,第二个用于分配对象持有的字符串。

所以

sizeof( c2 )

会给你对象占用内存的大小。

c2.capacity()

将为您提供对象分配用于存储字符串的大小以及将来可能会填充的一些其他字符。

When I use the following code cout << "The sizeof of c: " << sizeof(c); cout <<"The sizeof of c2: " << c2.length();

I get 6 and 5

如果你想比较字符串本身而不是字符数组所具有的终止零,那么你应该写

cout << "The length of c: " << std::strlen(c);
cout <<"The length of c2: " << c2.length();

你会得到结果 5 和 5。

您可以使用 std::string 类型的对象进行以下实验。

std::string s;

std::cout << sizeof( s ) << '\t' << s.capacity() << '\t' << s.length() << std::endl;

std::string s1( 1, 'A' );

std::cout << sizeof( s1 ) << '\t' << s1.capacity() << '\t' << s1.length() << std::endl;

std::string s3( 2, 'A' );

std::cout << sizeof( s2 ) << '\t' << s2.capacity() << '\t' << s2.length() << std::endl;

std::string s3( 16, 'A' );

std::cout << sizeof( s3 ) << '\t' << s3.capacity() << '\t' << s3.length() << std::endl;

关于c++ - 在 C++ 中,如何比较字符数组与字符串的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25729394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com