LENGTH()

size() and length() do exactly the same thing: they both return the number of characters in the string. They are interchangeable, using one the other is mostly a matter of style or readability.

This function is used to determine the number of characters in a string. It returns the length as a size_t value, which represents the total count of characters, excluding any null terminator. This function is commonly used in string processing tasks such as loops, validation, and formatting, allowing programmers to easily access string size without manually counting characters. Since it operates on std::string objects, it provides a safe and efficient way to work with dynamically managed text in modern C++ programs. Think of this as similar to strlen() in C. The size() and length() returns the same value and can be used interchangeably.

size_t std::string::length() const;

 * size_t: The return type is an unsigned integral type (usually unsigned int or unsigned long) that represents the number of characters in the string.
 * const: Indicates that calling length() does not modify the string.
 * std::string::: It is a member function of the std::string class.
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    std::cout << "Length: " << str.length() << std::endl;  // Output: Length: 5
    return 0;
}

Last updated