×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

string::length() Function with Example in C++ STL

C++ STL string::length() function: In this article, we are going to see how we can find string length using default length function?
Submitted by Radib Kar, on February 27, 2019

C++ STL - string::length() Function

In C, we know string basically a character array terminated by ‘\0’. Thus to operate with the string we define character array. But in C++, the standard library gives us the facility to use the string as a basic data type as an integer. We can easily find the length of the string using length() function.

Syntax

size_t string.length();

Parameter(s)

None

Return value

Return type: size_t

Sample Input and Output

Like we define and declare,

string s1="Include", s2="Help";
    
int i=s1.length(); //7
int j=s2.length(); //4

After concatenating:
    
string s3=s1+s2;
(s3 is "IcludeHelp")
int k=s3.length(); //11

string s4=s2+s1;
(s4 is "HelpInclude")
int r=s4.length(); //11

Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.

Header Files Needed

#include <string>
Or
#include <bits/stdc++.h>

Example

C++ program to demonstrate example of string::length() function:

#include <bits/stdc++.h>
using namespace std;

int main() {
  string s;

  cout << "enter string\n";
  cin >> s;

  cout << "length of the string is: " << s.length();

  return 0;
}

Output

enter string
IncludeHelp
length of the string is: 11

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.