Finding string class string length .length() .size() .c_str() methods – Computer Sir Ki Class


Code Learning#CPP#3009 siteicon   siteicon   siteicon  

Finding string class string length .length() .size() .c_str() methods

Program to demonstrate string class based string in c++ using different methods length() size() and conversion to c_str()

Learning Objectives

  • Finding number of characters in a string class based string using three different methods .length(), .size() and .c_str() in a null finding loop

Source Code

TC++ #3009

Source Code

#include <iostream>
#include <string>
using namespace std;
int main()
string s1="Trees can check pollution.";
cout<<"String = "<<s1<<endl;
cout<<"Length of string using <string object>.length() = "<<s1.length()<<endl;
cout<<"Length of string using <string object>.size() = "<<s1.size()<<endl;
int len;
cout<<"Length of string using null finding = "<<len<<endl;
return 0;

Test it !

Run Output

String = Trees can check pollution.
Length of string using <string object>.length() = 26
Length of string using <string object>.size() = 26
Length of string using null finding = 26

Code Understanding

string s1=”Trees can check pollution.”;
string s1 object has been initialised.

cout<<“String = “<<s1<<endl;
s1 object printed directly using cout

cout<<“Length of string using <string object>.length() = “<<s1.length()<<endl;
Here we find the number of characters in the string using length() method.

cout<<“Length of string using <string object>.size() = “<<s1.size()<<endl;
Here we find the number of characters using the size() method. length() and size() method are synonyms.

int len;
Here we run the loop to find the null after converting the string class based string to older c-style string using the function c_str().

cout<<“Length of string using null finding = “<<len<<endl;
Here we print the length using the older technique

Code Notes

  • After c++11 standard on wards the null at the end of string class based string can also be tested directly without converting it using c_str() method.
  • string class based string may not be supported on older DOS based compilers.


Common Errors

  • Student often forget to put round braces around methods of string object. for example s1.length is not correct. one has to write s1.length()

Suggested Filename(s): str-length-size.cpp,strlensz.cpp


sunmitra| Created: 25-Jan-2018 | Updated: 25-Jan-2018|