C++ Program to Find the Length of a String



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.

To learn all possible ways to find the length of a string, we recommend to visit this chapter: C++ - Finding String Length.

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

Open Compiler
#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

Open Compiler
#include <string.h> #include <iostream> 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
Updated on: 2024-12-05T13:40:33+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements