有两种计算 c++ 中字符串长度的方法:使用 strlen() 函数,适用于 c 风格字符串,不包含终止'\0'字符。使用 size() 方法,适用于 std::string 对象,包含终止'\0'字符,建议用于类型安全。

C++ 中计算字符串长度的方法
在 C++ 中,计算字符串长度有两种主要方法:
使用 strlen() 函数
strlen() 函数返回字符串中字符的数量(不包括终止'\0'字符):
<code class="cpp">#include <cstring>
int main() {
const char* str = "Hello World";
int length = strlen(str);
cout << "Length of \"" << str << "\": " << length << endl;
return 0;
}</code>使用 size() 方法
对于 std::string 对象,可以使用 size() 方法来获取字符串的长度。它返回字符的数量,包括终止'
对于 std::string 对象,可以使用 size() 方法来获取字符串的长度。它返回字符的数量,包括终止'\0'字符:
<code class="cpp">#include <string>
int main() {
std::string str = "Hello World";
int length = str.size();
cout << "Length of \"" << str << "\": " << length << endl;
return 0;
}</code>区别
-
strlen()函数适用于 C 风格的字符串(以'\0'结尾的字符数组),而size()方法适用于std::string对象。 -
strlen()不包括终止'\0'字符,而size()包括。
建议
对于 C 风格的字符串,建议使用 strlen() 函数,因为它更简洁。对于 std::string 对象,建议使用 size() 方法,因为它更加类型安全。
立即学习“C++免费学习笔记(深入)”;











