Introduction
When handling std::string in C++, there are frequently situations where you want to retrieve the “length” (i.e., how many characters are contained) of the string. For this purpose, the std::string class provides two member functions: .size() and .length(). In this article, I will explain how to use these functions and the relationship between them.
Sample Code Using .size() / .length()
This code calls both .size() and .length() on both an empty string and a string with a value, demonstrating that their return values are identical.
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "Hello, C++";
string empty_text;
// 1. Get the length of a string with a value
cout << "--- text ---" << endl;
cout << "Content: \"" << text << "\"" << endl;
cout << ".size() -> " << text.size() << endl;
cout << ".length() -> " << text.length() << endl;
// 2. Get the length of an empty string
cout << "\n--- empty_text ---" << endl;
cout << "Content: \"" << empty_text << "\"" << endl;
cout << ".size() -> " << empty_text.size() << endl;
cout << ".length() -> " << empty_text.length() << endl;
return 0;
}
Execution Result
--- text ---
Content: "Hello, C++"
.size() -> 10
.length() -> 10
--- empty_text ---
Content: ""
.size() -> 0
.length() -> 0
Code Explanation
.size() and .length() are Exactly the Same
In std::string, .size() and .length() are completely identical in both function and performance. Whichever you use, it returns the number of characters contained in the string as an unsigned integer type size_t.
Why Do Two Exist?
std::string came to have .size() for consistency with other containers (such as vector) during the standardization process of the C++ Standard Library (STL). On the other hand, the name .length() was also retained to be more intuitive, matching the conventions of many other programming languages.
Which one to use is entirely a matter of preference. However, you might consider using .size() if you want to unify the look of your code with other STL containers like vector or map, and using .length() if you want to clarify the intent of checking a string’s “length.”
Summary
In this article, I explained .size() and .length(), which are used to retrieve the character count of std::string in C++.
.size()and.length()are functionally identical.- They return the number of characters in the string.
- Which one to use is a matter of coding style or preference.
Retrieving the length of a string is a very basic operation, often used in conditions like for (size_t i = 0; i < my_string.length(); ++i).
