C++

C++ Program to Find the Length of a String

You can get the length of a string object by using a size() function or a length() function.

The size() and length() functions are just synonyms and they both do exactly same thing.


Example: Length of String Object

#include 
using namespace std;

int main()
{
    string str = "C++ Programming";

    // you can also use str.length()
    cout << "String Length = " << str.size();

    return 0;
}

Output

String Length = 15

Example: Length of C-style string

To get the length of a C-string string, strlen() function is used.

#include 
#include 
using namespace std;

int main()
{
    char str[] = "C++ Programming is awesome";

    // you can also use str.length()
    cout << "String Length = " << strlen(str);

    return 0;
}

Output

String Length = 26

Leave a Reply

Your email address will not be published. Required fields are marked *