Finding Length of a string in C++

0
129
Assignment Operator Overloading in C++
Program for Palindrome 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++
  2.  
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. int count(string);
  7.  
  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. }
  17.  
  18. int count(string s){
  19.     if(== “”)
  20.       return 0;
  21.     if(s.length() == 1)
  22.       return 1;
  23.     else
  24.         return (s.length());
  25.  
  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++.

Assignment Operator Overloading in C++
Program for Palindrome in C++

Leave a Reply