Google News
logo
CPP - Interview Questions
How to calculate length of a string in C++?
The length of a string can be calculated by using in-built functions such as length(), size(), strlen() and also by loops (while and for).
#include<iostream>
#include<cstring>
using namespace std;
main() {
   string s = "Free Time Learn";
   char arr[] = "Free Time Learn";
   cout << s.length();
   cout << s.size();
   cout <<strlen(arr);
 
   char *c = arr;
   int count = 0;
   while(*c != '\0'){
      count++;
      c++;
   }
   cout << count;
   count = 0;
   for(int i = 0; arr[i] != '\0'; i++){
      count++;
   }
   cout << count;
}

Output : 

1515151515

Advertisement