C++ Program to Find the Length of a String

This is a C++ Program to Find the Length of a String/Array.

Problem Description

The program takes a string or an array and prints its length.

Problem Solution

1. The program takes a string or an array.
2. Using inbuilt function, the length of the string is found.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Find the Length of a String/Array. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     char str[50];
  7.     int len;
  8.     cout << "Enter an array or string : ";
  9.     gets(str);
  10.     len = strlen(str);
  11.     cout << "Length of the string is : " << len;
  12.     return 0;
  13. }
Program Explanation

1. The user is asked to enter an array or a string and it is stored in the character variable ‘str’.
2. Using the function strlen() which is inbuilt under the library ‘string.h’, length of the string is found.
3. The result is then printed.

advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter an array or string : 1020304050
Length of the string is : 10
 
Case 2 :
Enter an array or string : hello
Length of the string is : 5
 
Case 3:
Enter an array or string : Program25
Length of the string is : 9

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.