Facebook Page Twitter Page LinkedIn Page
× C++ Tutorial C++ Advanced C++ Resources


The C++ string::length function is used find out the total number of characters in a string. The function returns the number of actual bytes that conform the contents of the string, and it is not necessarily equal to its storage capacity.

Note: Both string::length and string::size functions are synonyms and return the same value.

Syntax

size_t length() const;
size_t length() const noexcept;

Parameters

No parameter is required.

Return Type

Number of characters present in the string.

Time Complexity

Constant i.e, Θ(1)

Example:

In the below example, the string::length function is used find out the total number of characters in the string called MyString.

#include <iostream>
using namespace std;
 
int main (){
  string MyString = "Hello World!.";

  cout<<"The String is: "<<MyString<<"\n"; 
  cout<<"String length is: "<<MyString.length()<<"\n";
  cout<<"String size is: "<<MyString.size()<<"\n";
  return 0;
}

The output of the above code will be:

The String is: Hello World!.
String length is: 13
String size is: 13

❮ C++ - String Functions