C++ String size() function with example

In this article, let’s discuss one of the functions provided by the standard string class. C++ is an object-oriented programming language that has many classes in that one is std:: string class.

Strings in C++ :

In C++ strings are defined as an object with a sequence of characters( or bytes where one byte is mapped to one character). Each string ends with a terminating null character(‘\0‘). While accessing the characters in the string when we reach the ‘\0‘ character it represents we have reached the end of the string.

The syntax for declaring string object: 

string object_name;

Example  :

string str = "Codespeedy.com";

We externally cannot see the ‘\0‘ character at the end. Now let’s get into the topic which is about the size() function in the C++ string class.

size() string function with an example :

size() function in the string class is used to find the length of the string in terms of bytes(as we know each character is a byte in C++). When we call the function we do not pass any parameters. The function will return the length so the return type is an integer.

Syntax  : 

string_object.size();

Let’s see a code to understand it better. The following steps are followed in below code :

  1. Declare a string object with a name, let’s take str.
  2. While declaration itself let’s assign a string to it.
  3. Consider another variable of integer type to store the length of bytes of that string
  4. Finally, print the length as an output to the user.

Code :

#include <iostream>
using namespace std;
int main() {
    
    string str = "Codespeedy.com";
    int str_length = str.size();
    cout<<"Length of the string : "<<str_length<<"\n";
    return 0;
    
}

Output : 

Length of the string : 14

In C++, we can find the length of the string in many ways. like we can iterate a loop over the string until we encounter the null character and maintain a count of characters or we can use another built-in function called length() which performs as same as the size() function.

Hope you have understood the entire discussion.

Leave a Reply

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