WAP to find the length of a string
Objective
Write a C++ program to find the length of a string.
Algorithm / Approach
- Include the
<string>header. - Declare a
stringvariablename. - Use
getline(cin, name)to read a full string with spaces. - Call the built-in function
name.length()to get the character count. - Print the length.
main.cpp
#include<iostream>
using namespace std;
int main() {
string name;
cout<<"Enter a string : ";
getline(cin,name);
int len = name.length();
cout<<"Length = "<< len<< endl;
return 0;
}
Expected Output
Enter a string : cprowess Length = 8
Explanation of the Program
- Unlike traditional C-style character arrays, C++ provides a robust
stringclass with built-in utility functions. - Using
getline()instead ofcin >>is crucial here becausecin >>automatically stops reading as soon as it hits a space, whereasgetline()reads the entire line of input.
Complexity
Time Complexity
O(1) - When using the length() property.
Space Complexity
O(n) - To store the string.