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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.