What is the difference between .length() and strlen() ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

What is the difference between .length() and strlen() ?

1st Apr 2017, 8:50 AM
chris
chris - avatar
2 Answers
+ 15
Now this is a good question. Assuming we have: string str = "hello"; str.length() and strlen(str.c_str()) both returns 5. However, as you can see, we cannot do strlen(str). This is because strlen() only accepts const char* data type, which means that we have to convert string variable into const char* before passing it into strlen(). In the above example, I used c_str() for conversion. Function length() does not have this limitation.
1st Apr 2017, 8:56 AM
Hatsy Rei
Hatsy Rei - avatar
0
length() is more efficient than strlen() in the terms of latency.
2nd Apr 2017, 5:52 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar