How to get the length of a string using size() in C++

Overview

A string in C++ is used to store text. A string variable is one which contains a collection of characters that are enclosed by double quotes " ".

The string.size() function is simply used to get the length of a given string.

Syntax

string.size()

Parameter value

The string.size function takes no parameter value.

Return value

The string.size() function returns the length of a string.

Code

See the code below.

#include <iostream>
#include <string>
using namespace std;
int main() {
//creating a string variable
string name = "Theophilus";
// using the size() function
cout << "The length of the string is: " << name.size();
return 0;
}

Free Resources