C++ String Length

String Length is the number of characters in a string.

There are many ways in which you can find the length of a string in C++. In this tutorial, we will go through some of the processes that use builtin methods, and some of the processes using looping techniques.

C++ String length using string.length()

length() is a member function of string class that returns the length of this string.

In the following example program, we shall take a string, and find its length using length() function.

C++ Program

#include <iostream>
using namespace std;

int main() {
   string str = "save trees";
   int len = str.length();
   cout << "String Length : " << len << endl;
}

Output

String Length : 10
Program ended with exit code: 0

C++ String length using string.size()

size() is a member function of string class that returns the number of characters in this string.

In the following example program, we shall take a string, and find its length using size() function.

C++ Program

#include <iostream>
using namespace std;

int main() {
   string str = "save trees";
   int len = str.size();
   cout << "String Length : " << len << endl;
}

Output

String Length : 10
Program ended with exit code: 0

C++ String length using strlen()

strlen() is a member function of cstring library. The function returns the number of characters between the beginning of the string and the terminating null character of the char array passed as argument.

In the following example program, we shall take a C style string, char array, and find its length using strlen() function.

To use strlen() function, you have to include cstring header file at the start of your program.

C++ Program

#include <iostream>
#include <cstring>
using namespace std;

int main() {
   char str[] = "save trees";
   int len = strlen(str);
   cout << "String Length : " << len << endl;
}

Output

String Length : 10
Program ended with exit code: 0

C++ String length using While Loop

If you are just starting with C++ programming, it is always good to know the basics. You can find the length of the string using a while loop. This allows you to understand how a string is stored and the limits to identify a string.

In while loop, we start with the first character and continue with subsequent characters until we find null character \0.

In the following example program, we shall take a string, and find its length using C++ While Loop.

C++ Program

#include <iostream>
using namespace std;

int main() {
    char str[] = "save trees";
    
    char *ch = str;
    int len = 0;
    while(*ch != '\0'){
        len++;
        ch++;
    }
   
    cout << "String Length : " << len << endl;
}

Output

String Length : 10
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the length of a string using builtin functions, other libraries, while loop, etc.