We all know arrays of chars are known as strings in C++. We can store chars in a string. So, today we are going to learn about the methods of finding the length of a string or we can say a program to calculate how many chars are stored in the string.
title: "C++ length of string"
tags: cpp
canonical_url: https://kodlogs.com/blog/248/how-to-get-the-length-of-the-string-in-c
Methods
Using while loop : using loops to find the string length is an old fashioned way of doing it. Initializing loop from zero and then incrementing it till the end of the string.
Using for loop : similar to while loop, to initialize the counter equal to zero till the end of the string.
Using function strlen() : C library provides the function size_t strlen(const char*str) which computed the length of the string for us. But it does not include the terminating null character.
Using string::size : This method returns the size of the string but in terms of bytes.
Using string::length : Both string::size and string::length works similarly, they return the size of the string in terms of bytes.
Program
This is a universal program. What I mean by universal is that all of the methods are defined in this program down below.
int main()
{
string str= "lengthofthestring";
// method using size()
cout << str.size() << endl;
// method using length()
cout << str.length() << endl;
// method using while loop
int i=0;
while (str[i])
i++;
cout << i << endl;
//method using for loop
for (i = 0; str[i]; i++)
;
cout << i <<endl;
//method strlen()
cout << strlen(str.c_str()) << endl;
return 0;
}
Top comments (1)
I wouldn't use
strlen()