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

Overview

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

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

Syntax

string.length()

Parameters

The length function takes no parameters.

Return value

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

Code

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

Explanation

  • Line 7: We created a string variable.
  • Line 10: We used the length() function and displayed the result.

Free Resources