Differences between length() size() and C strlen() of C + + string member functions

1. Function declaration

C++ string member function length() is the same as size(), but strlen() is different from C library function. First take a look at the declaration of the three functions:

//返回string长度,单位字节
size_t length() const noexcept;

//返回string长度,单位字节。作用等同于length()
size_t size() const noexcept;

//C标准库函数,返回C风格字符串长度,单位字节
size_t strlen ( const char * str );

2. Use example

in real projects, when C++ string gets the length, we often use the following two methods.

//方法一:调用length()或size()
string strTest="test";
strTest.length();			//结果为4
strTest.size();				//结果为4

//方法二:转为C风格字符串,调用strlen()
strlen(strTest.c_str());	//结果为4

the above code snippet takes a string length of 4 and makes no difference, so what’s the difference between method 1 and method 2?See the following code:

char buf[256]={0};
buf[0]='a';
buf[2]='v';
buf[3]='h';

string strTest(buf,6);
cout<<"strTest[0]:"<<(uint32_t)strTest[0]<<"_"<<(uint32_t)strTest[1]<<"_"<<(uint32_t)strTest[2]<<"_"<<(uint32_t)strTest[3]<<"_"<<(uint32_t)strTest[4]<<"_"<<(uint32_t)strTest[5]<<endl;
cout<<"strTest.length()="<<strTest.length()<<" strTest.size()="<<strTest.size()<<" strlen(strTest.c_str())="<<strlen(strTest.c_str())<<endl;
cout<<"strTest:"<<strTest<<endl;

output:

strTest[0]:97_0_118_104_0_0
strTest.length()=6 strTest.size()=6 strlen(strTest.c_str())=1
strTest:avh

Conclusion

3.

(1) when a string contains the null character ‘\0’, the length of the string is truncated using strlen(), and the member functions length() and size() are used to return the true length of the string.
(2) cout will filter out null characters when it outputs string, and the output will not be truncated.
(3) when constructing or stitching a string, it is recommended to specify the length of the string at the same time, such as

//构造时使用
string strTest(buf,6);
//而非,因为会被截断
string strTest(buf);

//拼接时使用
strTest.append(buf,6);
//而非,因为会被截断
strTest+=buf;

reference

[1] C++ reference

Read More: