Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find the length of a string

C++ Code Example — String Programs

ADVERTISEMENT

WAP to find the length of a string

Objective

Write a C++ program to find the length of a string.

Algorithm / Approach

  1. Include the <string> header.
  2. Declare a string variable name.
  3. Use getline(cin, name) to read a full string with spaces.
  4. Call the built-in function name.length() to get the character count.
  5. 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 string class with built-in utility functions.
  • Using getline() instead of cin &gt;&gt; is crucial here because cin &gt;&gt; automatically stops reading as soon as it hits a space, whereas getline() reads the entire line of input.

Complexity

Time Complexity O(1) - When using the length() property.
Space Complexity O(n) - To store the string.
ADVERTISEMENT