C++ Program to Find the Length of a String

C++ProgrammingServer Side Programming

A string is a one dimensional character array that is terminated by a null character. The length of a string is the number of characters in the string before the null character.

For example.

char str[] = “The sky is blue”;
Number of characters in the above string = 15

A program to find the length of a string is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   char str[] = "Apple";
   int count = 0;
   while (str[count] != '\0')
   count++;
   cout<<"The string is "<<str<<endl;
   cout <<"The length of the string is "<<count<<endl;
   return 0;
}

Output

The string is Apple
The length of the string is 5

In the above program, the count variable is incremented in a while loop until the null character is reached in the string. Finally the count variable holds the length of the string. This is given as follows.

while (str[count] != '\0')
count++;

After the length of the string is obtained, it is displayed on screen. This is demonstrated by the following code snippet.

cout<<"The string is "<<str<<endl;
cout<<"The length of the string is "<<count<<endl;

The length of the string can also be found by using the strlen() function. This is demonstrated in the following program.

Example

 Live Demo

#include<iostream>
#include<string.h>
using namespace std;
int main() {
   char str[] = "Grapes are green";
   int count = 0;
   cout<<"The string is "<<str<<endl;
   cout <<"The length of the string is "<<strlen(str);
   return 0;
}

Output

The string is Grapes are green
The length of the string is 16
raja
Published on 27-Sep-2018 17:05:58
Advertisements