Program to find the length of the given string by using functions

Written by

Garvit Gulati

Introduction to string and functions:

C++ Standard template library includes a header file called “string”. 

The string header file provides us a data type called “string” with a variety of functions to make our life easier.

Syntax:

string <string_name>;

We can access each element of the string just like we access our character array strings(str[index]).

But they offer us a lot of advantages over the traditional character arrays, for instance, the string length function which is implemented in the given code.

Algorithm:

  1. First, we will input a string from the user(whose length is to be found) and store it in a string variable s.
  2. Then we will print the length of the string using the length function(s.length()).

Code:

#include <iostream>
#include <string>  //for using string data type
#include <cstdio>  //for using getline function to input string
using namespace std;

int main(){
	string s;
	cout << "Enter a string\n";
	getline(cin, s);  //taking input in the string
	cout << "Length of the given string=" << s.length();
}

Output

Enter a string
Hello World
Length of the given string=11

Program to find the length of the given string by using functions