std::size_t strlen( const char* str );
str
指向的首元素到以首个空字符\0
结尾的字符串的字符数,注意:不包含\0
。表达式(expression)或类型(type)
),获得表达式(expression)或类型(type)
的对象表示的字节数。表达式(expression)
,获得表达式(expression)
的类型的对象表示的字节数。sizeof a; //正确 sizeof int;//错误
\0
const char str[] = "How"; std::cout << "without null character: " << std::strlen(str) << '\n' << "with null character: " << sizeof str << '\n'; /* without null character: 3 with null character: 4 */
sizeof str2
实际是计算指针所占的空间大小,在64位系统下为8个字节。const char str[] = "How"; const char* str2 = "How"; std::cout << "strlen of str: " << std::strlen(str) << '\n' << "strlen of str2: " << std::strlen(str2) << '\n'; std::cout << "sizeof of str: " << sizeof str << '\n' << "sizeof of str2: " << sizeof str2 << '\n'; /* strlen of str: 3 strlen of str2: 3 sizeof of str: 4 sizeof of str2: 8 */
char str3[10]="How";
只能加9个字符,因为还要留一个给\0
.char str3[10]="How"; std::cout << "strlen of str3: " << std::strlen(str3) << '\n' << "sizeof of str3: " << sizeof(str3) << '\n'; /* strlen of str3: 3 sizeof of str3: 10 */