5 Different methods to find length of a string in C++?


Here we will see five different ways to get the string lengths in C++. In C++ we can use the traditional character array string, and C++ also has String class. In different area there are different methods of calculating the string lengths.

The C++ String class has length() and size() function. These can be used to get the length of a string type object. To get the length of the traditional C like strings, we can use the strlen() function. That is present under the cstring header file. Another two approaches are straight forward. One by using the while loop, and another is by using the for loop.

Let us see the examples to get the idea.

Example

 Live Demo

#include<iostream>
#include<cstring>
using namespace std;
main() {
   string myStr = "This is a sample string";
   char myStrChar[] = "This is a sample string";
   cout << "String length using string::length() function: " << myStr.length() <<endl;
   cout << "String length using string::size() function: " << myStr.size() <<endl;
   cout << "String length using strlen() function for c like string: " << strlen(myStrChar) <<endl;
   cout << "String length using while loop: ";
   char *ch = myStrChar;
   int count = 0;
   while(*ch != '\0'){
      count++;
      ch++;
   }
   cout << count << endl;
   cout << "String length using for loop: ";
   count = 0;
   for(int i = 0; myStrChar[i] != '\0'; i++){
      count++;
   }
   cout << count;
}

Output

String length using string::length() function: 23
String length using string::size() function: 23
String length using strlen() function for c like string: 23
String length using while loop: 23
String length using for loop: 23

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements