Thursday, May 13, 2021
Home C / C++ Finding Length of a string in C++

Finding Length of a string in C++

Sometimes we have strings entered by the user and we need to find out the length of a string or size of that length of a string to be used further. For this purpose we use a library “string” which is having lots of built in function for lots of purposes, and here is one we can use for finding out length of a string. That is not that difficult. The code is given below:

  1. // Finding length of a string in C++
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. int count(string);
  8. int main()
  9. {
  10.     string str;
  11.     cout << “Enter a string: “;
  12.     getline(cin,str);
  13.     cout << “nString: “ << str << endl;
  14.     cout << count(str) << endl;
  15.     return 0;
  16. }
  18. int count(string s){
  19.     if(== “”)
  20.       return 0;
  21.     if(s.length() == 1)
  22.       return 1;
  23.     else
  24.         return (s.length());
  26. }

Now in the above code we took a string entered by the user and then passed it to a function named “count”, the function count takes a string as its argument. Now what this function do is that it finds out the length of a string that the user entered. In this function we used a condition that if the string size is null or empty then return 0, if length of the string is 1, then return 1, else return the string length calculated by the function “s.length()”. This function does not takes any argument and it is a member function of class string , and it all for length of a string in C++.

- Advertisment -

Most Popular

Android Webview Tutorial With Example | How to Use Webview in Android

Android Webview Tutorial With Example Have you seen an Android app displaying Web content using Webview. This Android Webview Tutorial is about integrating Webview using Android Studio....

Student Registration Project in PHP

In this Student Registration Project we are providing a form in simple html to the student and that form sends the data to "student.php"...

Java GUI Calculator Source Code

Here we have a Java GUI Calculator Source Code for you in which a Java GUI calculator has been created using "swing" and "awt". The calculator has...

Numeric Array in PHP

Numeric arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero....