Home »
C++ STL
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
String as datatype
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.
Prototype:
size_t string.length();
Parameter: None
Return type: size_t
Example:
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 file needed:
#include <string>
Or
#include <bits/stdc++.h>
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