C++ Standard Library C++ STL Library

C++ <string> - size() Function



The C++ string::size function is used find out the total number of characters in a string. It 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::size and string::length functions are synonyms and return the same value.

Syntax

size_type size() const;
size_type size() const noexcept;

Parameters

No parameter is required.

Return Value

Number of characters present in the string.

Time Complexity

Constant i.e, Θ(1)

Example:

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

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string MyString = "Hello World!.";

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

The output of the above code will be:

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

❮ C++ <string> Library

5