C++ for Beginners: C++ Program to Find the Length of a String

Hits: 10

(C++ programming Example for Beginners)

C++ Program to Find the Length of a String

In this example, you will learn to compute the length (size) of a string (both string objects and C-style strings).


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 <iostream>
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 <iostream>
#include <cstring>
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

 

C++ for Beginners: C++ Program to Find the Length of a String

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.