In this tutorial, we will learn how to find the length of a string in C++ using different techniques.
In C++, can write string either as string object or as char array (also known as C style string).
For string object, we can use size()
or length()
method to get the length of the string and for C-type string we can use strlen()
or sizeof()
function.
Let’s see an example of each.
Example 1: length of String Object using size()
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { string str = "Pencil Programmer"; cout << "Length: " << str.size(); return 0; } |
output
1 | length: 17 |
Example 2: length of String Object using length()
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { string str = "Programming Simplified"; cout << "Length: " << str.length(); return 0; } |
output
1 | length: 22 |
Example 3: length of C-style string using strlen()
For C-style string (string formed using char array), we can use strlen()
function. Make sure you include
library before using this function.
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> #include <cstring> using namespace std; int main() { char str[] = "Pencil Programmer"; cout << "Length: " << strlen(str); return 0; } |
output
1 | length: 17 |
Example 4: Length of C-Style string using sizeof()
sizeof()
function in C++ returns the size of string or array in terms of bytes. So if we use use sizeof(str)
it will return number of characters * size of char.
We can divide the result by sizeof(str[0])
i.e size of single character, to get the number of characters in the string.
But wait, string formed using char array ends with ‘\0’, which is an extra character included in the length. Therefore we need to deduct 1 from out final result to get the true length of the string.
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> using namespace std; int main() { char str[] = "Pencil Programmer"; int length = sizeof(str)/sizeof(str[0]) -1; cout << "Length: " << length; return 0; } |
output
1 | length: 17 |
Comment below if you have any suggestions or doubts.