获得cstring的大小

时间:2013-03-16 18:02:20

标签: c++

有没有办法获得以null结尾的字符串的大小?

实施例

char* buffer = "an example";

unsigned int buffer_size; // I want to get the size of 'buffer'

2 个答案:

答案 0 :(得分:7)

请注意,在C ++ 11中,字符串文字的类型为const char[],而转换为char*(即指向非const的指针)非法。这说:

#include <cstring> // You will need this for strlen()
#include <iostream>

int main()
{
    char const* buffer = "an example";
    //   ^^^^^
    std::cout << std::strlen(buffer);
}

但是,由于您正在编写C ++而不是C(至少这是标记所声称的),您应该使用C ++标准库中的类和算法:

#include <string> // You will need this for std::string
#include <iostream>

int main()
{
    std::string buffer = "an example";
    std::cout << buffer.length();
}

查看live example

注意:

如果您使用的API需要C字符串,则可以使用c_str()对象的std::string成员函数来检索指向您的char const*指针使用包含封装C字符串的std :: string对象内存缓冲区的c_str()成员函数。请记住,您无法修改该缓冲区的内容:

std::string s = "Hello World!";
char const* cstr = s.c_str();

答案 1 :(得分:3)

strlen(buffer)尝试<cstring>。它返回传入的字符串的长度。