Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
function
c++
length
communitycreator

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

Onyejiaku Theophilus Chidalu

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.

RELATED TAGS

string
function
c++
length
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring